Loading/Downloading image from URL on Swift

前端 未结 30 2619
感动是毒
感动是毒 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:02

    Swift 4::

    This will shows loader while loading the image. You can use NSCache which store image temporarily

    let imageCache = NSCache()
    extension UIImageView {
        func loadImageUsingCache(withUrl urlString : String) {
            let url = URL(string: urlString)
            if url == nil {return}
            self.image = nil
    
            // check cached image
            if let cachedImage = imageCache.object(forKey: urlString as NSString)  {
                self.image = cachedImage
                return
            }
    
            let activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView.init(activityIndicatorStyle: .gray)
            addSubview(activityIndicator)
            activityIndicator.startAnimating()
            activityIndicator.center = self.center
    
            // if not, download image from url
            URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in
                if error != nil {
                    print(error!)
                    return
                }
    
                DispatchQueue.main.async {
                    if let image = UIImage(data: data!) {
                        imageCache.setObject(image, forKey: urlString as NSString)
                        self.image = image
                        activityIndicator.removeFromSuperview()
                    }
                }
    
            }).resume()
        }
    }
    

    Usage:-

    truckImageView.loadImageUsingCache(withUrl: currentTruck.logoString)
    

提交回复
热议问题