一个简单的网络Image缓存类

2017-10-25  本文已影响27人  狂奔的胖蜗牛

该类的主要作用是,下载以及缓存图片,用了很少的代码,很实用。

代码如下

import Foundation
import UIKit

public class YHImageLoader {
    
    var cache = NSCache<NSString, NSData>()
    
    /// 单例
    static let sharedLoader = YHImageLoader()
    
    /// 下载图片
    ///
    /// - Parameters:
    ///   - urlString: 图片url
    ///   - completionHandler: 图片下载完成后的回调
    public func imageForUrl(urlString: String, completionHandler: @escaping(_ image: UIImage?, _ url: String) -> ()) {
        //子线程中下载,并且可以在后台下载
        DispatchQueue.global(qos: DispatchQoS.QoSClass.background).async {
            var data: NSData?
            //从缓存中读取
            if let dataCache = self.cache.object(forKey: urlString as NSString) {
                data = dataCache as NSData
            }else {
                //缓存中没有,假如url是一个文件路径
                if (URL(string: urlString) != nil) {
                    data = NSData(contentsOf: URL(string: urlString)!)
                    if data != nil {
                        self.cache.setObject(data!, forKey: urlString as NSString)
                    }
                }else {
                    //假如路径时错误的,返回
                    return
                }
            }
            //数据是存在的
            if let goodData = data {
                let image = UIImage(data: goodData as Data)
                DispatchQueue.main.async{
                    completionHandler(image, urlString)
                }
                return
            }
            //数据不存在,下载
            URLSession.shared.dataTask(with: URL(string: urlString)!, completionHandler: { (data, response, error) in
                if (error != nil) {
                    completionHandler(nil, urlString)
                    return
                }
                if data != nil {
                    let image = UIImage(data: data!)
                    self.cache.setObject(data! as NSData, forKey: urlString as NSString)
                    DispatchQueue.main.async {
                        completionHandler(image, urlString)
                    }
                    return
                }
            }).resume()
        }
    }
}

使用

import UIKit

class ViewController: UIViewController {

    var image: UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        image = UIImageView(frame: view.frame)
        view.addSubview(image)
        YHImageLoader.sharedLoader.imageForUrl(urlString: "https://ss1.baidu.com/6ONXsjip0QIZ8tyhnq/it/u=1427822428,3741610415&fm=173&s=CCB707D069FB3B86C28DD507030080C9&w=640&h=353&img.JPG") { [weak self] (image, url) in
            if let weakSelf = self {
                weakSelf.image.image = image
            }
        }
    }

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

逻辑如下

上一篇下一篇

猜你喜欢

热点阅读