用于在UICollectionView中下载和显示图像的UIImageView扩展

时间:2016-06-05 12:23:11

标签: swift uiimageview uiimage uicollectionview nsurlsession

我已经制作并扩展了UIImageView,允许我异步下载图像,然后根据他们的特定索引(CollectionView中的IndexPath)将它们分配给他们的ImageView。它工作得很好,唯一的问题是:

  • 在快速滚动和停止时,我仍然看到错误的图像。

有人能帮帮我吗?这是我的代码:

// UIImageView扩展:

extension ExtendedUIImageView {

func downloadFrom(link link:String, contentMode mode: UIViewContentMode, imageIndex: Int) {

    if (NSFileManager.defaultManager().fileExistsAtPath(link)) {
        self.image = UIImage(contentsOfFile: link)
        return
    }

    self.imageURL = NSURL(string: link)
    let url = NSURL(string: link)
    contentMode = mode

    NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in
        guard
            let httpURLResponse = response as? NSHTTPURLResponse where httpURLResponse.statusCode == 200,
            let mimeType = response?.MIMEType where mimeType.hasPrefix("image"),
            let data = data where error == nil,
            let image = UIImage(data: data)
            else { return }
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            if (url == self.imageURL) {
                self.image = image
            }
        }
    }).resume()
  }
}

//并且我可以像这样调用这个方法:

self.previewImageView?.downloadFrom(link: localPath, contentMode: .ScaleAspectFill, imageIndex: cell.indexPath.item)

//其中:

var previewImageView: ExtendedUIImageView?

请帮助我:-O

2 个答案:

答案 0 :(得分:2)

您好〜我以前一直试图做同样的事情。这就是我做的。对我来说这很简单,工作正常没有任何问题。

import Foundation
import UIKit

extension UIImageView {


    //load image async from inaternet
    func loadFromURL(photoUrl:String){
        //NSURL
        let url = NSURL(string: photoUrl)
        //Request
        let request = NSURLRequest(URL:url!);
        //Session
        let session = NSURLSession.sharedSession()
        //Data task
        let datatask = session.dataTaskWithRequest(request) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
            if error != nil {
                print(error?.localizedDescription)
            }
            dispatch_async(dispatch_get_main_queue()) {
                self.image = UIImage(data: data!)
            }
        }
        datatask.resume()
    }


}

答案 1 :(得分:0)

使用翠鸟进行缓存

import Foundation
import UIKit
import Kingfisher

public extension UIImageView {
    func loadAvatar(url: URL) {
        self.kf.setImage(with: url, placeholder: UIImage(named: "default-avatar"), options: [.transition(.fade(0.2))])
    }

    func setImageWithIndicator(url: URL) {
        self.kf.indicatorType = .activity
        self.kf.setImage(with: url)
    }
}