Loading/Downloading image from URL on Swift

前端 未结 30 2504
感动是毒
感动是毒 2020-11-21 05:39

I\'d like to load an image from a URL in my application, so I first tried with Objective-C and it worked, however, with Swift, I\'ve a compilation error:

30条回答
  •  温柔的废话
    2020-11-21 06:01

    class ImageStore: NSObject { 
        static let imageCache = NSCache()
    }
    
    extension UIImageView {
        func url(_ url: String?) {
            DispatchQueue.global().async { [weak self] in
                guard let stringURL = url, let url = URL(string: stringURL) else {
                    return
                }
                func setImage(image:UIImage?) {
                    DispatchQueue.main.async {
                        self?.image = image
                    }
                }
                let urlToString = url.absoluteString as NSString
                if let cachedImage = ImageStore.imageCache.object(forKey: urlToString) {
                    setImage(image: cachedImage)
                } else if let data = try? Data(contentsOf: url), let image = UIImage(data: data) {
                    DispatchQueue.main.async {
                        ImageStore.imageCache.setObject(image, forKey: urlToString)
                        setImage(image: image)
                    }
                }else {
                    setImage(image: nil)
                }
            }
        }
    }
    

    Usage :

    let imageView = UIImageView()
    imageView.url("image url")
    

提交回复
热议问题