NSCache to store images for UITableView In Swift

邮差的信 提交于 2019-12-08 03:42:01

问题


I'm new in swift programming and I have searched a lot about storing images with NSCache using Swift.

What I have done so far is that I'm getting ids and imageNames with JSON and I have my data in array and I was able to display image in cells with no problem. Now I want to cache images. This is the code that I have written:

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, How can I store and retrieve images with cache?


回答1:


I recommend you to check this library HanekeSwift (It provides a memory and LRU disk cache for UIImage, NSData, JSON, String or any other type that can be read or written as data), at least to understand how they are dealing with cache, and you can decide to use it or create your own solution.

Using a very easy/simple 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)

Using the cache

let cache = Shared.dataCache

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

// Eventually...

cache.fetch(key: "image.png").onSuccess { data in
     // Do something with data
}


来源:https://stackoverflow.com/questions/29004336/nscache-to-store-images-for-uitableview-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!