Loading/Downloading image from URL on Swift

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

    Swift 4.1 I have crated a function just pass image url, cache key after image is generated set it to completion block.

       class NetworkManager: NSObject {
    
      private var imageQueue = OperationQueue()
      private var imageCache = NSCache()
    
      func downloadImageWithUrl(imageUrl: String, cacheKey: String, completionBlock: @escaping (_ image: UIImage?)-> Void) {
    
        let downloadedImage = imageCache.object(forKey: cacheKey as AnyObject)
        if let  _ = downloadedImage as? UIImage {
          completionBlock(downloadedImage as? UIImage)
        } else {
          let blockOperation = BlockOperation()
          blockOperation.addExecutionBlock({
            let url = URL(string: imageUrl)
            do {
              let data = try Data(contentsOf: url!)
              let newImage = UIImage(data: data)
              if newImage != nil {
                self.imageCache.setObject(newImage!, forKey: cacheKey as AnyObject)
                self.runOnMainThread {
                  completionBlock(newImage)
                }
              } else {
                completionBlock(nil)
              }
            } catch {
              completionBlock(nil)
            }
          })
          self.imageQueue.addOperation(blockOperation)
          blockOperation.completionBlock = {
            print("Image downloaded \(cacheKey)")
          }
        }
      }
    }
    extension NetworkManager {
      fileprivate func runOnMainThread(block:@escaping ()->Void) {
        if Thread.isMainThread {
          block()
        } else {
          let mainQueue = OperationQueue.main
          mainQueue.addOperation({
            block()
          })
        }
      }
    }
    

提交回复
热议问题