使用Kingfisher库仅获取UIImage。

57
我需要获取一个UIImage,而不是使用Kingfisher库来加载普通的UIImageView。
为了实现这一点,我使用了UIImageView的一个解决方法:
let imageView = UIImageView()

imageView.kf_setImageWithURL(NSURL(string: cpa.imageName)!, placeholderImage: nil,
        optionsInfo: [.Transition(ImageTransition.Fade(1))],
        progressBlock: { receivedSize, totalSize in
            print("\(receivedSize)/\(totalSize)")
        },
        completionHandler: { image, error, cacheType, imageURL in
            anView!.image = image //anView IS NOT an UIImageView
            anView!.frame.size = CGSize(width: 15.0, height: 15.0)
            print("Finished")
    })

这段代码完美运行,但我希望以更简洁的方式实现。这个库中是否有一种方法只获取UIImage?异步和缓存。
9个回答

83
你可以使用KingfisherManagerretrieveImage(with:options:progressBlock:completionHandler:)方法来实现这个功能。
也许像这样:
KingfisherManager.shared.retrieveImage(with: url, options: nil, progressBlock: nil, completionHandler: { image, error, cacheType, imageURL in
    print(image)
})

2
在Swift 3中,它被烦人地重命名为KingfisherManager.shared.retrieveImage(with: url!, options: nil, progressBlock: nil) { (image, error, cacheType, imageURL) -> () in print(image) } - Jaime Agudo
这个也会缓存图片吗? - DoesData
2
@DoesData 是的,它可以。 - Dmitrij Rogov
@DmitrijRogov 需要做什么才能将图像存储到缓存中吗? - Adrian
它是缓存在内存还是磁盘中? - Matloob Hasnain
这是旧语法,请更新答案以明确说明。 - sgelves

48

这是在Kingfisher 5中下载图片的最新语法(已在Swift 4.2中测试)

func downloadImage(`with` urlString : String){
    guard let url = URL.init(string: urlString) else {
        return
    }
    let resource = ImageResource(downloadURL: url)

    KingfisherManager.shared.retrieveImage(with: resource, options: nil, progressBlock: nil) { result in
        switch result {
        case .success(let value):
            print("Image: \(value.image). Got from: \(value.cacheType)")
        case .failure(let error):
            print("Error: \(error)")
        }
    }
}
如何调用上述函数。
self.downloadImage(with: imageURL) //replace with your image url

1
资源是一个URL(“url-string”)对象,因此对于来自其他语言的人来说并不清楚。此外,您可以删除发送nil的参数,并在您不关心图像未加载时删除完成处理程序。 - sgelves

12

使用新的Swift 3版本,您可以使用ImageDownloader:

ImageDownloader.default.downloadImage(with: url, options: [], progressBlock: nil) {
    (image, error, url, data) in
    print("Downloaded Image: \(image)")
}

ImageDownloader是Kingfisher的一部分,因此不要忘记import Kingfisher


5
根据此中的cachePolicy: .reloadIgnoringLocalCacheData,这将不会利用缓存,这也是使用Kingfisher而不是其他更简单方法的原因。 - Jaime Agudo

10

Swift 5:

我将在 @Hardik Thakkar 的回答基础上进行完善,添加一个更改以便你可以使用闭包返回图像,可能会对某些人有所帮助:

func downloadImage(with urlString : String , imageCompletionHandler: @escaping (UIImage?) -> Void){
        guard let url = URL.init(string: urlString) else {
            return  imageCompletionHandler(nil)
        }
        let resource = ImageResource(downloadURL: url)
        
        KingfisherManager.shared.retrieveImage(with: resource, options: nil, progressBlock: nil) { result in
            switch result {
            case .success(let value):
                imageCompletionHandler(value.image)
            case .failure:
                imageCompletionHandler(nil)
            }
        }
    }

如何调用:

 downloadImage(with :yourUrl){image in
     guard let image  = image else { return}
      // do what you need with the returned image.
 }

6

Swift 5

Kingfisher 5

此代码百分之百可行。

YourImageView.kf.setImage(with: URL(string: imagePath), placeholder: nil, options: nil, progressBlock: nil, completionHandler: { result in
switch result {
    case .success(let value):
                print("Image: \(value.image). Got from: \(value.cacheType)")
    case .failure(let error):
                print("Error: \(error)")
    }
})

//OR
let resource = ImageResource(downloadURL: picUrl!)
KingfisherManager.shared.retrieveImage(with: resource, options: nil, progressBlock: nil) { result in
    switch result {
        case .success(let value):
        print("Image: \(value.image). Got from: \(value.cacheType)")
        imageProfile = value.image
        case .failure(let error):
            print("Error: \(error)")
        }
    }

6

在Kingfisher 5中的另一种方法:

KingfisherManager.shared.retrieveImage(with: url) { result in
    let image = try? result.get().image
    if let image = image {
        ...
    }
}

2
在使用此函数时,调用实例方法'retrieveImage'未找到精确匹配。 - BluE_MoOn

6

0
如果您想从API调用中自定义UILabel而不是UIImageView。
import Kingfisher

func getImage(imageUrl: String,title:String?=nil){

        let someTitle = UILabel()
        view.addSubview(someTitle)
        someTitle.text = title
        someTitle.isHidden = true
       
        someTitle.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
        someTitle.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
        someTitle.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
        someTitle.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true

        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { [self] in
            let url = URL(string: imageUrl )
            yourImage.kf.setImage(
                with: url,
                placeholder:  (someTitle as? Placeholder),
                options: [
                    .loadDiskFileSynchronously,
                    .cacheOriginalImage,
                    .transition(.fade(0.25))
                ],
                completionHandler: { result in
                    // Done
                    switch result {
                    case .success(let value):
                         self.yourImage.image = value.image
                    case .failure(let error):
                        someTitle.isHidden = false
                    }
                }
            )
                        
        }
    }

只需在您的控制器中调用该函数


getImage(imageUrl: you_url, title: your_name)


0

如果你想要一个自定义的UIImage和UIImageView

let url = URL(string: "https://iosacademy.io/assets/images/brand/icon.jpg")

override func viewDidLoad() {
    super.viewDidLoad()
    addPicture()
    
}

private func addPicture() {
    let containerView = UIView()
    //let myImage = UIImage(named: "Old Scroll Lengmei") // to add UIImage  by code
    let myImage = UIImage()
    let myImageView = UIImageView() // to add UIImageView by code
    let label = UILabel() // to add Label by code
    
    myImageView.kf.setImage(with: url)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接