您好,登錄后才能下訂單哦!
詳解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 ?? "") } }) }
如有疑問請留言或者到本站社區交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。