NSOperation做图片异步下载

图片的异步加载

class DataModel: NSObject {

    var name = ""
    var icon = ""
    var download = ""
    
    
    init(dict:NSDictionary) {
        
        self.name = dict["name"] as! String
        self.icon = dict["icon"] as! String
        self.download = dict["download"] as! String
    }
    
///图片缓存目录
let ImageCache_Path = NSHomeDirectory()+"/Library/Caches/imageCache"

class ViewController: UITableViewController {
    
    //MARK: - 属性
    //1.数据源数组
    lazy var dataArray:[DataModel] = {
    
        return self.getData()
    }()
    
    //2.任务队列
    lazy var queue:NSOperationQueue = {
    
        var tQueue = NSOperationQueue()
        
        //设置最大并发数
        tQueue.maxConcurrentOperationCount = 3
        
        return tQueue
    }()
    
    //3.图片缓存
    //NSCache是一种和字典一样的容器类。通过键值对的形式去存储数据。和字典相比,NSCache在程序接受到内存警告的时候,会自动的去删除自己存储的数据
    lazy var imageCache:NSCache = {
        
    
        return NSCache()
    }()
    
    //4.任务缓存
    lazy var operationCache:NSMutableDictionary = {
    
        return NSMutableDictionary()
    }()
    
    
    
    //MARK: - 生命周期
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //1.注册cell
        self.tableView.registerNib(UINib.init(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "cell")
        
        //2.设置行高
        self.tableView.rowHeight = 120
        
        //3.在沙盒目录下创建缓存图片的文件夹
        //在指定目录下创建一个文件夹
        //参数1:需要创建的文件夹的目录
        //参数2:是否创建中间目录
        //参数3:文件夹的属性(nil -> 默认属性)
        do{
            try NSFileManager.defaultManager().createDirectoryAtPath(ImageCache_Path, withIntermediateDirectories: true, attributes: nil)
        }catch{
        
            print("已经存在")
        }
        
        
    }

    //在程序接受到内存警告的时候会自动调用的方法
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
        //删除缓存
        self.operationCache.removeAllObjects()  //删除字典中所有的数据
    
    }
}


//MARK: -  tableView 协议方法
extension ViewController{

    //1.设置cell的个数
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return self.dataArray.count
    }
    
    //2.创建cell
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        //1.创建cell
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! TableViewCell
        
        //2.刷新数据
        let model = self.dataArray[indexPath.row]
        
        cell.nameLabel.text = model.name
        cell.downloadLabel.text = model.download
        //a.判断缓存中是否已经有对应的图片
        if self.imageCache.objectForKey(model.icon) != nil {
            
            cell.iconImageView.image = self.imageCache.objectForKey(model.icon) as? UIImage
            
            return cell
        }else{
            
            //b.去本地查看是否有本地缓存
            //获取当前cell对应数据中的图片
            let fileName = (model.icon as! NSString).lastPathComponent
            //拼接文件对应的路径
            let path = ImageCache_Path + "/" + fileName
            //获取本地文件
            let data = NSData.init(contentsOfFile: path)
            //判断是否找到了对应的本地图片
            if data != nil {
                let image = UIImage.init(data: data!)
                //保存到程序的缓存
                self.imageCache.setObject(image!, forKey: model.icon)
                //显示图片
                cell.iconImageView.image = image
                
                print("获取本地数据")
                
                //返回
                return cell
            }
            
            
            
            //c.如果本地缓存没有再做网络请求
            //图片没有下载出来的时候,显示默认图片
            cell.iconImageView.image = UIImage.init(named: "user_default.png")
            
            //异步下载图片
            self.downloadImage(indexPath)
        }
        
        
        //3.返回cell
        return cell
        
    }
}

//MARK: - 图片的异步下载
extension ViewController{

    func downloadImage(indexPath:NSIndexPath) {
        let model = self.dataArray[indexPath.row]
        
        
        //1.判断当前这个下载任务是否已经创建过
        if (self.operationCache.objectForKey(model.icon) != nil) {
            
            return
        }
        
        //2.异步加载图片
        //注意:只要是网络上的图片就必须要异步加载
        let operation = NSBlockOperation.init {
            
            //1.下载图片
            let data = NSData.init(contentsOfURL: NSURL.init(string: model.icon)!)
            
            if data == nil{
            
                print("网络错误")
                return
            }
            
            let image = UIImage.init(data: data!)
            
            //2.将数据保存到程序的缓存中
            //将model.icon作为key,image作为值存到imageCache中
            self.imageCache.setObject(image!, forKey: model.icon)
            
            //3.保存到本地一份
            //将二进制数据写入到指定的文件中
            //参数1:文件路径
            //参数2:是否进行原子操作 -> 是否异步进行写的操作
            //取到icon的最后一个部分,作为文件名
            let iconStr = model.icon as NSString
            let lastStr = iconStr.lastPathComponent
            data?.writeToFile(ImageCache_Path+"/"+lastStr, atomically: false)
            
            //4.回到主线程
            NSOperationQueue.mainQueue().addOperationWithBlock({
                
                //刷新cell
                self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
            })
            
        }
        self.queue.addOperation(operation)
        //将任务保存到缓存
        self.operationCache.setObject(operation, forKey: model.icon)
    }
}



//MARK: - 获取数据
extension ViewController{

    func getData() -> [DataModel] {
        var tempArray = [DataModel]()
        
        //1.获取plist文件路径
        let path = NSBundle.mainBundle().pathForResource("model.plist", ofType: nil)
        
        //2.拿到plist文件中的数组
        let plistArray = NSArray.init(contentsOfFile: path!)
        
        //3.遍历数组拿到所有的字典
        for item in plistArray! {
            
            let dict = item as! NSDictionary
            
            //4.根据字典去创建对应的数据模型
            let model = DataModel.init(dict: dict)
            
            //5.将模型保存到数组中
            tempArray.append(model)
        }
        
        
        return tempArray
    }

SDWebImage的使用

import UIKit

//在swift中使用OC的第三方库
//1.将第三方库的文件拖到工程中
//2.创建桥接文件
//a.通过新建文件创建一个.h文件,命名规范:XXX-Briding-Header
//b.在桥接文件中将需要使用的头文件通过"#import"包含进去
//c.设置工程文件

class ViewController: UITableViewController {
    
    //MARK: - 属性
    //1.数据源数组
    lazy var dataArray:[DataModel] = {
    
        return self.getData()
    }()
    
    //MARK: - 生命周期
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //1.注册cell
        self.tableView.registerNib(UINib.init(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "cell")
        
        //2.设置行高
        self.tableView.rowHeight = 120
        
        print(NSHomeDirectory())
    }

    //在程序接受到内存警告的时候会自动调用的方法
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    
    }
}


//MARK: -  tableView 协议方法
extension ViewController{

    //1.设置cell的个数
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return self.dataArray.count
    }
    
    //2.创建cell
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        //1.创建cell
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! TableViewCell
        
        //2.刷新数据
        let model = self.dataArray[indexPath.row]
        
        cell.nameLabel.text = model.name
        cell.downloadLabel.text = model.download
        //通过SDWebImage做图片的异步下载和缓存
        //参数1:图片的网路路径对应的url
        //参数2:占位图
        //cell.iconImageView.setImageWithURL(NSURL.init(string: model.icon), placeholderImage: UIImage.init(named: "user_default"))
        cell.iconImageView.sd_setImageWithURL(NSURL.init(string: model.icon), placeholderImage: UIImage.init(named: "user_default"))
        
    
        //3.返回cell
        return cell
        
    }
}

//MARK: - 获取数据
extension ViewController{

    func getData() -> [DataModel] {
        var tempArray = [DataModel]()
        
        //1.获取plist文件路径
        let path = NSBundle.mainBundle().pathForResource("model.plist", ofType: nil)
        
        //2.拿到plist文件中的数组
        let plistArray = NSArray.init(contentsOfFile: path!)
        
        //3.遍历数组拿到所有的字典
        for item in plistArray! {
            
            let dict = item as! NSDictionary
            
            //4.根据字典去创建对应的数据模型
            let model = DataModel.init(dict: dict)
            
            //5.将模型保存到数组中
            tempArray.append(model)
        }
        
        
        return tempArray
    }

图片的异步加载封装

import UIKit

//sd_setImageWithURL(NSURL.init(string: model.icon), placeholderImage: UIImage.init(named: "user_default"))

extension UIImageView{

    
    func yt_setImage(urlStr:String,placeholderImageName:String) {
        //创建图片缓存的文件夹
        do{
            try NSFileManager.defaultManager().createDirectoryAtPath(ImageCache_Path, withIntermediateDirectories: true, attributes: nil)
        }catch{}
        
        //判断当前这个图片是否有本地缓存
        let fileName = (urlStr as NSString).lastPathComponent
        let getData = NSData.init(contentsOfFile: ImageCache_Path+"/"+fileName)
        if getData != nil {
            
            self.image = UIImage.init(data: getData!)
            return
        }else{
        
            //如果没有本地图片显示占位图
            self.image = UIImage.init(named: placeholderImageName)
        }
        
        
        
        //下载图片
        dispatch_async(dispatch_get_global_queue(0, 0)) { 
            //1.异步下载图片
            let data = NSData.init(contentsOfURL: NSURL.init(string: urlStr)!)
            if data == nil{
            
                print("网络错误")
                return
            }
            let image = UIImage.init(data: data!)
            
            //2.将图片保存到本地
            data?.writeToFile(ImageCache_Path+"/"+fileName, atomically: true)
            
            //3.回到主线程显示图片
            dispatch_async(dispatch_get_main_queue(), { 
                
                self.image = image
            })
        }
        
    }
}

///图片缓存目录
let ImageCache_Path = NSHomeDirectory()+"/Library/Caches/imageCache"

class ViewController: UITableViewController {
    
    //MARK: - 属性
    //1.数据源数组
    lazy var dataArray:[DataModel] = {
    
        return self.getData()
    }()
    
    //2.任务队列
    lazy var queue:NSOperationQueue = {
    
        var tQueue = NSOperationQueue()
        
        //设置最大并发数
        tQueue.maxConcurrentOperationCount = 3
        
        return tQueue
    }()
    
    //3.图片缓存
    //NSCache是一种和字典一样的容器类。通过键值对的形式去存储数据。和字典相比,NSCache在程序接受到内存警告的时候,会自动的去删除自己存储的数据
    lazy var imageCache:NSCache = {
        
    
        return NSCache()
    }()
    
    //4.任务缓存
    lazy var operationCache:NSMutableDictionary = {
    
        return NSMutableDictionary()
    }()
    
    
    
    //MARK: - 生命周期
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //1.注册cell
        self.tableView.registerNib(UINib.init(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "cell")
        
        //2.设置行高
        self.tableView.rowHeight = 120
        
        print(NSHomeDirectory())
        
        
        
        
    }

    //在程序接受到内存警告的时候会自动调用的方法
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
        //删除缓存
        self.operationCache.removeAllObjects()  //删除字典中所有的数据
    
    }
}


//MARK: -  tableView 协议方法
extension ViewController{

    //1.设置cell的个数
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return self.dataArray.count
    }
    
    //2.创建cell
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        //1.创建cell
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! TableViewCell
        
        //2.刷新数据
        let model = self.dataArray[indexPath.row]
        
        cell.nameLabel.text = model.name
        cell.downloadLabel.text = model.download
        
        cell.iconImageView.yt_setImage(model.icon, placeholderImageName: "user_default.png")
        
        
        //3.返回cell
        return cell
        
    }
}

//MARK: - 图片的异步下载
extension ViewController{

    func downloadImage(indexPath:NSIndexPath) {
        let model = self.dataArray[indexPath.row]
        
        
        //1.判断当前这个下载任务是否已经创建过
        if (self.operationCache.objectForKey(model.icon) != nil) {
            
            return
        }
        
        //2.异步加载图片
        //注意:只要是网络上的图片就必须要异步加载
        let operation = NSBlockOperation.init {
            
            //1.下载图片
            let data = NSData.init(contentsOfURL: NSURL.init(string: model.icon)!)
            
            if data == nil{
            
                print("网络错误")
                return
            }
            
            let image = UIImage.init(data: data!)
            
            //2.将数据保存到程序的缓存中
            //将model.icon作为key,image作为值存到imageCache中
            self.imageCache.setObject(image!, forKey: model.icon)
            
            //3.保存到本地一份
            //将二进制数据写入到指定的文件中
            //参数1:文件路径
            //参数2:是否进行原子操作 -> 是否异步进行写的操作
            //取到icon的最后一个部分,作为文件名
            let iconStr = model.icon as NSString
            let lastStr = iconStr.lastPathComponent
            data?.writeToFile(ImageCache_Path+"/"+lastStr, atomically: false)
            
            //4.回到主线程
            NSOperationQueue.mainQueue().addOperationWithBlock({
                
                //刷新cell
                self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
            })
            
        }
        self.queue.addOperation(operation)
        //将任务保存到缓存
        self.operationCache.setObject(operation, forKey: model.icon)
    }
}



//MARK: - 获取数据
extension ViewController{

    func getData() -> [DataModel] {
        var tempArray = [DataModel]()
        
        //1.获取plist文件路径
        let path = NSBundle.mainBundle().pathForResource("model.plist", ofType: nil)
        
        //2.拿到plist文件中的数组
        let plistArray = NSArray.init(contentsOfFile: path!)
        
        //3.遍历数组拿到所有的字典
        for item in plistArray! {
            
            let dict = item as! NSDictionary
            
            //4.根据字典去创建对应的数据模型
            let model = DataModel.init(dict: dict)
            
            //5.将模型保存到数组中
            tempArray.append(model)
        }
        
        

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 14,752评论 4 61
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 176,663评论 25 709
  • 今天回来,我发现屋子里被盗了,那台用了几年的笔记本电脑就这样没了。 发生这种事情,我内心还是受到了震动的,足以打破...
    吉日良辰阅读 1,436评论 8 2
  • 01别拍了,有什么事我负责! 刚从学校毕业,我就进了一家low逼公司。 这个公司的人力资源说的最溜的三句话是:我司...
    暴躁杂货铺阅读 2,726评论 0 1
  • 二狗坐在风驰电掣般的高铁上,脑海里浮现的画面早已让他欲哭无泪,中午接到二叔的电话他就快马加鞭的往家赶,生怕连最后一...
    张张张瑞新阅读 3,318评论 0 3

友情链接更多精彩内容