詳解Swift 利用Opration和OprationQueue來下載網(wǎng)絡(luò)圖片
成都創(chuàng)新互聯(lián)公司是一家專注于成都網(wǎng)站制作、網(wǎng)站建設(shè)與策劃設(shè)計,長安網(wǎng)站建設(shè)哪家好?成都創(chuàng)新互聯(lián)公司做網(wǎng)站,專注于網(wǎng)站建設(shè)10年,網(wǎng)設(shè)計領(lǐng)域的專業(yè)建站公司;建站業(yè)務(wù)涵蓋:長安等地區(qū)。長安做網(wǎng)站價格咨詢:18980820575
1. 基于Opration封裝的獲取網(wǎng)絡(luò)數(shù)據(jù)組件
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、創(chuàng)建URL下載地址 let url:URL! = URL(string:self.imageUrl!); //2、創(chuàng)建Request對象 var urlRequest:URLRequest = URLRequest(url:url); urlRequest.httpMethod = "GET" urlRequest.httpShouldUsePipelining = true; //不需要緩存 //urlRequest.cachePolicy = .reloadIgnoringLocalCacheData //3、創(chuàng)建會話 let config = URLSessionConfiguration.default let session = URLSession(configuration: config, delegate:self, delegateQueue: .main) //4、下載任務(wù) //2>-- -- URLSessionDataDelegate 模式 let loadDataTask = session.dataTask(with: urlRequest) //5、啟動任務(wù) loadDataTask.resume() } //初始化一個data,用來存儲下載下來的數(shù)據(jù) private var _responseData: NSMutableData! var responseData: NSMutableData!{ get{ if _responseData == nil { _responseData = NSMutableData() } return _responseData } set{ self._responseData = newValue } } } // MARK - URLSessionDataDelegate 模式獲取數(shù)據(jù) extension LJOpreationManager:URLSessionDataDelegate { @available(iOS 7.0, *) func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Swift.Void) { //允許繼續(xù)加載數(shù)據(jù) 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----數(shù)據(jù)下載完畢") //將接收的數(shù)據(jù)結(jié)果回調(diào)到前臺,用于進度展示 weakSelf?.ljcallBackClosure!(data as Data ,nil) } } } }
2. 基于OprationQueue封裝的網(wǎng)絡(luò)數(shù)據(jù)管理組件
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模式下載圖片或者數(shù)據(jù)*/ _ = 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 ?? "") } }) }
如有疑問請留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!