Kingfisher and swift 3 - cannot set image with url

2019-04-12 19:07发布

问题:

Checking the documentation and the migration guide, I should be able to set a new image using this code:

imageView.kf.setImage(with:url ...) 

but actually I cannot find this method in the library, I only see:

imageView.kf.setImage(with:Resource... )

I don't know exactly how this resource shoud work though since I cannot find anything in the documentation.

回答1:

Resource is a protocol. URL has been extended to conform to this protocol. So you can do:

let url = URL(string: ...)!
imageView.kf.setImage(with: url)

If you want some control over what Kingfisher uses for the key in its cache, you can use ImageResource:

let identifier = "..."
let url = URL(string: "http://example.com/images/identifier=\(identifier)")!
let resource = ImageResource(downloadURL: url, cacheKey: identifier)

imageView.kf.setImage(with: resource)


回答2:

I fixed that issue using this:

PhotoHelper.shared.imagePickedBlock = { [weak self] (image, url) in
      self?.imageView.kf.setImage(with: url, placeholder: image, options: nil, progressBlock: nil, completionHandler: { imageResult, error, type, cache in
        self?.imageView.image = image
      })
    }

PhotoHelper is wrapper on native Image Picker:

    func imagePickerController(_ picker: UIImagePickerController,     didFinishPickingMediaWithInfo info: [String : Any]) {
          currentVC.dismiss(animated: true, completion: {
            if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
              let url = info[UIImagePickerControllerReferenceURL] as! URL
              self.imagePickedBlock?(image, url)
             }
          })
      }


回答3:

For Swift 4.2

import Kingfisher

extension UIImageView {
    func setImage(with urlString: String){
        guard let url = URL.init(string: urlString) else {
            return
        }
        let resource = ImageResource(downloadURL: url, cacheKey: urlString)
        var kf = self.kf
        kf.indicatorType = .activity
        self.kf.setImage(with: resource)
    }
}

How to use

self.imgVw.setImage(with: your image url)