详解Swift 利用Opration和OprationQueue来下载网络图片
1. 基于Opration封装的获取网络数据组件
import Foundation import UIKit public typealias OpreatiOnClosure= ((_ data:Data? , _ error: Error?) -> Void) class LJOpreationManager: Operation { /** * 下载用的url */ public var imageUrl : String? /** * 定义闭包属性,可选类型 */ public var ljcallBackClosure : OpreationClosure? func initWitParamter(_ url: String, _ callback: @escaping OpreationClosure) -> LJOpreationManager { if url != "" { self.imageUrl = url self.ljcallBackClosure = callback } return self } //MARK: -- start override func start() { print("start ljManager method") self.startRequest() } func startRequest() { //1、创建URL下载地址 let url:URL! = URL(string:self.imageUrl!); //2、创建Request对象 var urlRequest:URLRequest = URLRequest(url:url); urlRequest.httpMethod = "GET" urlRequest.httpShouldUsePipelining = true; //不需要缓存 //urlRequest.cachePolicy = .reloadIgnoringLocalCacheData //3、创建会话 let cOnfig= URLSessionConfiguration.default let session = URLSession(configuration: config, delegate:self, delegateQueue: .main) //4、下载任务 //2>-- -- URLSessionDataDelegate 模式 let loadDataTask = session.dataTask(with: urlRequest) //5、启动任务 loadDataTask.resume() } //初始化一个data,用来存储下载下来的数据 private var _responseData: NSMutableData! var responseData: NSMutableData!{ get{ if _respOnseData== nil { _respOnseData= NSMutableData() } return _responseData } set{ self._respOnseData= newValue } } } // MARK - URLSessionDataDelegate 模式获取数据 extension LJOpreationManager:URLSessionDataDelegate { @available(iOS 7.0, *) func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Swift.Void) { //允许继续加载数据 completionHandler(.allow) } @available(iOS 7.0, *) func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { //每次获取的data在此拼装 //print("Data......\(data)") self.responseData.append(data) let currentBytes :Float = Float(self.responseData.length) let allTotalBytes :Float = Float((dataTask.response?.expectedContentLength)!) let proValu :Float = Float(currentBytes/allTotalBytes) print("URLSessionDataDelegate----下载进度:------\(proValu*100)%"); } func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { if ljcallBackClosure != nil ,let data = self.responseData{ weak var weakSelf : LJOpreationManager? = self DispatchQueue.main.async { print("URLSessionDataDelegate----数据下载完毕") //将接收的数据结果回调到前台,用于进度展示 weakSelf?.ljcallBackClosure!(data as Data ,nil) } } } }
2. 基于OprationQueue封装的网络数据管理组件
import Foundation class LJWebImageManager: NSObject { /// Shared manager used . public static let shared = LJWebImageManager() public var ljquee = OperationQueue() override init() { if #available(iOS 8.0, *) { self.ljquee.qualityOfService = .background } else { } } public func requestByUrl(_ url: String,_ callback: @escaping OpreationClosure) -> LJOpreationManager { let operation = LJOpreationManager().initWitParamter(url, callback) ljquee.addOperation(operation) return operation } }
3. 此处下载一张图片
func setCellData(_ labelNameStr:String, imageUrlStr:String) { titleLabel.text = labelNameStr as String /* Session 的delegate模式下载图片或者数据*/ _ = LJWebImageManager.shared.requestByUrl(imageUrlStr, { (data, error) in if error == nil, data != nil { let newImage = UIImage(data: data! as Data) DispatchQueue.main.async{ let titleImage = UIImageView(frame: CGRect(x: 0, y: 5, width: 40, height: 40)) titleImage.image = newImage self.contentView.addSubview(titleImage) } } else { print(error ?? "") } }) }
如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!