将图像快速缓存

时间:2019-01-25 22:05:36

标签: swift image caching

我正在解析数据并检查图像是否在缓存中。如果是,则将其设置,如果未将其设置为默认值,则将其发送到缓存。

将其发送到缓存的部分始终为nil ???

任何帮助将不胜感激

Pic_STR =“ https://myserver/Pictures/” + Pic +“ .jpg”                 let url = URL(string:Pic_STR)

            if let imageFromCache = imageCache.object(forKey: Pic_STR as AnyObject) as? UIImage {
                data.photo = imageFromCache
                return
            } else {
                data.photo = UIImage(named: "Default")
                let imageCache = NSCache<NSString, AnyObject>()
                URLSession.shared.dataTask(with: url!) { data, response, error in
                    guard let data = data, error == nil else { return }

                        let imageToCache = UIImage(data: data)
                        imageCache.setObject(imageToCache!, forKey: self.Pic_STR as NSString)
                        //self.image = imageToCache

                    }.resume()
            }

1 个答案:

答案 0 :(得分:0)

经过反复试验,我终于找到了解决方案。我相信它可以改进,但是可以。我希望使用扩展程序,但不知道如何使用。

struct imageData {
    let image: UIImage?
    let name: String?
}

var newImage = UIImage()
var myImages = [imageData]()


   let imageString= "https://myserver/Pictures/" + Pic + ".jpg"
            let imageURL = URL(string: imageString)

            CON2 = false

            for pics in myImages {
                if pics.name == Pic {
                    data.photo = pics.image
                    CON2 = true
                }
            }

            if CON2 == false {
                let data2 = try? Data(contentsOf: imageURL!)

                if let imageData = data2 {
                    newImage = UIImage(data: imageData)!
                }

                let newData = imageData(image: newImage, name: Pic) as imageData
                myImages += [newData]
                data.photo = newImage
            }