Swift异步加载图像

时间:2016-05-04 05:07:29

标签: swift asynchronous

我正在处理来自url异步的show image。我试图为下载图像创建一个新线程,然后在main thread上刷新。

func asyncLoadImg(product:Product,imageView:UIImageView){
    let downloadQueue = dispatch_queue_create("com.myApp.processdownload", nil)
    dispatch_async(downloadQueue){
        let data = NSData(contentsOfURL: NSURL(string: product.productImage)!)
        var image:UIImage?
        if data != nil{
            image = UIImage(data: data!)
        }
        dispatch_async(dispatch_get_main_queue()){
            imageView.image = image
        }

    }
}

当我尝试调试时,当涉及到dispatch_async(downloadQueue)时,它会跳出func。有什么建议吗? THX

7 个答案:

答案 0 :(得分:87)

Swift 3.0+更新代码:(从 jamesrochabrun 链接https://github.com/jamesrochabrun/JSONTutorialFinal获取帮助)

let imageCache = NSCache<NSString, UIImage>()

extension UIImageView {

    func imageFromServerURL(_ URLString: String, placeHolder: UIImage?) {

        self.image = nil
        if let cachedImage = imageCache.object(forKey: NSString(string: URLString)) {
            self.image = cachedImage
            return
        }

        if let url = URL(string: URLString) {
            URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in

                //print("RESPONSE FROM API: \(response)")
                if error != nil {
                    print("ERROR LOADING IMAGES FROM URL: \(error)")
                    DispatchQueue.main.async {
                        self.image = placeHolder
                    }
                    return
                }
                DispatchQueue.main.async {
                    if let data = data {
                        if let downloadedImage = UIImage(data: data) {
                            imageCache.setObject(downloadedImage, forKey: NSString(string: URLString))
                            self.image = downloadedImage
                        }
                    }
                }
            }).resume()
        }
    }
}

Swift 3更新代码:

extension UIImageView {
    public func imageFromServerURL(urlString: String) {
        self.image = nil
        URLSession.shared.dataTask(with: NSURL(string: urlString)! as URL, completionHandler: { (data, response, error) -> Void in

            if error != nil {
                print(error)
                return
            }
            DispatchQueue.main.async(execute: { () -> Void in
                let image = UIImage(data: data!)
                self.image = image
            })

        }).resume()
    }}

Swift 2.2代码:

 extension UIImageView {
        public func imageFromServerURL(urlString: String) {
    self.image = nil
            NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: urlString)!, completionHandler: { (data, response, error) -> Void in

                if error != nil {
                    print(error)
                    return
                }
                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    let image = UIImage(data: data!)
                    self.image = image
                })

            }).resume()
        }}

现在,您只需要执行此操作即可从服务器网址加载图片:

  1. 使用占位符图片使用swift 3.0 +更新的代码: UIImageView.imageFromServerURL(URLString:&#34; here server url&#34;,placeHolder:uiimage格式的占位符图片)

  2. Swfit 3或以下: UIImageView.imageFromServerURL(&#34; here server url&#34;)

  3. 简单!

答案 1 :(得分:22)

extension中使用Swift3。要解决网络问题,我建议您使用NSCache

import UIKit

let imageCache = NSCache<NSString, AnyObject>()

extension UIImageView {
    func loadImageUsingCache(withUrl urlString : String) {
        let url = URL(string: urlString)
        self.image = nil

        // check cached image
        if let cachedImage = imageCache.object(forKey: urlString as NSString) as? UIImage {
            self.image = cachedImage
            return
        }

        // if not, download image from url
        URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in
            if error != nil {
                print(error!)
                return
            }

            DispatchQueue.main.async {
                if let image = UIImage(data: data!) {
                    imageCache.setObject(image, forKey: urlString as NSString)
                    self.image = image
                }
            }

        }).resume()
    }
}

希望有所帮助!

答案 2 :(得分:3)

继续从Shobhakar Tiwari的回答中,我认为在这些情况下通常有助于在出现错误时拥有默认图像,并且出于加载目的,我已将其更新为包含可选默认值图像:

Swift 3

extension UIImageView {
public func imageFromServerURL(urlString: String, defaultImage : String?) {
    if let di = defaultImage {
        self.image = UIImage(named: di)
    }

    URLSession.shared.dataTask(with: NSURL(string: urlString)! as URL, completionHandler: { (data, response, error) -> Void in

        if error != nil {
            print(error ?? "error")
            return
        }
        DispatchQueue.main.async(execute: { () -> Void in
            let image = UIImage(data: data!)
            self.image = image
        })

    }).resume()
  }
}

答案 3 :(得分:1)

此代码可能会对您有所帮助。

   let cacheKey = indexPath.row
   if(self.imageCache?.objectForKey(cacheKey) != nil){
           cell.img.image = self.imageCache?.objectForKey(cacheKey) as? UIImage
    }else{
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), {
             if let url = NSURL(string: imgUrl) {
                  if let data = NSData(contentsOfURL: url) {
                            let image: UIImage = UIImage(data: data)!
                            self.imageCache?.setObject(image, forKey: cacheKey)
                            dispatch_async(dispatch_get_main_queue(), {
                                cell.img.image = image
                            })
                        }
                    }
                })
            }

使用此图像将下载并缓存而不会滞后表视图滚动

答案 4 :(得分:1)

此解决方案可以快速滚动,无需不必要的图像更新。 您必须将url属性添加到我们的单元类:

class OfferItemCell: UITableViewCell {
    @IBOutlet weak var itemImageView: UIImageView!
    @IBOutlet weak var titleLabel: UILabel! 
    var imageUrl: String?
}

并添加扩展程序:

import Foundation
import UIKit

let imageCache = NSCache<AnyObject, AnyObject>()
let imageDownloadUtil: ImageDownloadUtil = ImageDownloadUtil()

extension OfferItemCell {
    func loadImageUsingCacheWithUrl(urlString: String  ) {
         self.itemImageView.image = nil
        if let cachedImage = imageCache.object(forKey: urlString as AnyObject) as? UIImage {
            self.itemImageView.image = cachedImage
            return
        }
        DispatchQueue.global(qos: .background).async {
            imageDownloadUtil.getImage(url: urlString, completion: {
                image in
                DispatchQueue.main.async {
                    if self.imageUrl == urlString{
                        imageCache.setObject(image, forKey: urlString as AnyObject)
                     self.itemImageView.image = image
                    }
                }
            })
        }
    }
}

您还可以改进它并将一些代码提取到更通用的单元类,即CustomCellWithImage,以使其更具可重用性。

答案 5 :(得分:1)

加载没有in SWIFT 4blink效果的异步图片的最常见方式changing images用于自定义UIImageView类,如下所示:

//MARK: - 'asyncImagesCashArray' is a global varible cashed UIImage
var asyncImagesCashArray = NSCache<NSString, UIImage>()

class AyncImageView: UIImageView {

//MARK: - Variables
private var currentURL: NSString?

//MARK: - Public Methods

func loadAsyncFrom(url: String, placeholder: UIImage?) {
    let imageURL = url as NSString
    if let cashedImage = asyncImagesCashArray.object(forKey: imageURL) {
        image = cashedImage
        return
    }
    image = placeholder
    currentURL = imageURL
    guard let requestURL = URL(string: url) else { image = placeholder; return }
    URLSession.shared.dataTask(with: requestURL) { (data, response, error) in
        DispatchQueue.main.async { [weak self] in
            if error == nil {
                if let imageData = data {
                    if self?.currentURL == imageURL {
                        if let imageToPresent = UIImage(data: imageData) {
                            asyncImagesCashArray.setObject(imageToPresent, forKey: imageURL)
                            self?.image = imageToPresent
                        } else {
                            self?.image = placeholder
                        }
                    }
                } else {
                    self?.image = placeholder
                }
            } else {
                self?.image = placeholder
            }
        }
    }.resume()
}
}

UITableViewCell下面使用此类的示例:

class CatCell: UITableViewCell {

//MARK: - Outlets
@IBOutlet weak var catImageView: AyncImageView!

//MARK: - Variables

var urlString: String? {
    didSet {
        if let url = urlString {
            catImageView.loadAsyncFrom(url: url, placeholder: nil)
        }
    }
}

override func awakeFromNib() {
    super.awakeFromNib()
}
}

答案 6 :(得分:0)

最好的方法之一是使用SDWebImage

Swift示例:

import SDWebImage
imageView.sd_setImage(with: URL(string: "ImageUrl"), placeholderImage: UIImage(named: "placeholder.png"))

目标C示例:

#import <SDWebImage/UIImageView+WebCache.h>
[imageView sd_setImageWithURL:[NSURL URLWithString:@"ImageUrl"]
         placeholderImage:[UIImage imageNamed:@"placeholder.png"]];