1

私は迅速なプログラミングが初めてで、Swiftを使用してNSCacheで画像を保存することについて多くのことを検索しました。

私がこれまでに行ったことは、JSON でids とs を取得していて、データを配列に持っていて、問題なくセルに画像を表示できたことです。imageName今、私は画像をキャッシュしたいと思っています。これは私が書いたコードです:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as TableViewCell

        //cell.imageView
         nameID = self.hoge[indexPath.row]["cars"]["carid"].string!
        cell.nameLabel.text = nameID

        if let imageFileURL = imageCache.objectForKey(self.hoge[indexPath.row]["cars"]["carid"].intValue) as? NSURL {
            println("Get image from cache")

        } else {

            imageName = self.hoge[indexPath.row]["cars"]["pic_name"].string!

            // If the image does not exist, we need to download it
            var imgURL: NSURL = NSURL(string: "http://192.168.1.35/car/uploads/" + imageName )!

            var image:UIImage = UIImage(named: "pen")!
            // Download an NSData representation of the image at the URL
            let request: NSURLRequest = NSURLRequest(URL: imgURL)
            NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!) -> Void in
                if error == nil {
                    image = UIImage(data: data)!
                    cell.viewCell.image = image

                }
                else {
                    println("Error: \(error.localizedDescription)")
                }
            })

        }

        return cell
    }

SO、キャッシュを使用して画像を保存および取得するにはどうすればよいですか?

4

1 に答える 1

5

このライブラリHanekeSwiftを確認することをお勧めします(これは、UIImage、NSData、JSON、String、またはデータとして読み書きできるその他のタイプのメモリと LRU ディスク キャッシュを提供します)。少なくとも、キャッシュの処理方法を理解するために、それを使用するか、独自のソリューションを作成するかを決定できます。

非常に簡単でシンプルな API の使用:

// Setting a remote image
imageView.hnk_setImageFromURL(url)

// Setting an image manually. Requires you to provide a key.
imageView.hnk_setImage(image, key: key)

キャッシュの使用

let cache = Shared.dataCache

cache.set(value: data, key: "image.png")

// Eventually...

cache.fetch(key: "image.png").onSuccess { data in
     // Do something with data
}
于 2015-03-12T07:53:24.190 に答える