Loading/Downloading image from URL on Swift

前端 未结 30 2509
感动是毒
感动是毒 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 05:56

    Swift 4: A simple loader for small images (ex: thumbnails) that uses NSCache and always runs on the main thread:

    class ImageLoader {
    
      private static let cache = NSCache()
    
      class func image(for url: URL, completionHandler: @escaping(_ image: UIImage?) -> ()) {
    
        DispatchQueue.global(qos: DispatchQoS.QoSClass.background).async {
    
          if let data = self.cache.object(forKey: url.absoluteString as NSString) {
            DispatchQueue.main.async { completionHandler(UIImage(data: data as Data)) }
            return
          }
    
          guard let data = NSData(contentsOf: url) else {
            DispatchQueue.main.async { completionHandler(nil) }
            return
          }
    
          self.cache.setObject(data, forKey: url.absoluteString as NSString)
          DispatchQueue.main.async { completionHandler(UIImage(data: data as Data)) }
        }
      }
    
    }
    

    Usage:

    ImageLoader.image(for: imageURL) { image in
      self.imageView.image = image
    }
    

提交回复
热议问题