詳解Swift 利用Opration和OprationQueue來下載網(wǎng)絡(luò)圖片
詳解Swift 利用Opration和OprationQueue來下載網(wǎng)絡(luò)圖片
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對(duì)象
var urlRequest:URLRequest = URLRequest(url:url);
urlRequest.httpMethod = "GET"
urlRequest.httpShouldUsePipelining = true;
//不需要緩存
//urlRequest.cachePolicy = .reloadIgnoringLocalCacheData
//3、創(chuàng)建會(huì)話
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config, delegate:self, delegateQueue: .main)
//4、下載任務(wù)
//2>-- -- URLSessionDataDelegate 模式
let loadDataTask = session.dataTask(with: urlRequest)
//5、啟動(dòng)任務(wù)
loadDataTask.resume()
}
//初始化一個(gè)data,用來存儲(chǔ)下載下來的數(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----下載進(jìn)度:------\(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)到前臺(tái),用于進(jìn)度展示
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ǐng)留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
相關(guān)文章
iOS Xcode創(chuàng)建文件時(shí)自動(dòng)生成的注釋方法
下面小編就為大家分享一篇iOS Xcode創(chuàng)建文件時(shí)自動(dòng)生成的注釋方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-01-01
iOS 二維碼掃描相關(guān)功能實(shí)現(xiàn)
這篇文章主要介紹了iOS 二維碼掃描相關(guān)功能實(shí)現(xiàn),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-09-09
iOS下拉刷新 UIScrollVie異常閃動(dòng)問題
這篇文章主要介紹了iOS下拉刷新 UIScrollVie異常閃動(dòng)問題,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2017-03-03
iOS11 SectionHeader 胡亂移動(dòng)且滑動(dòng)時(shí)出現(xiàn)重復(fù)內(nèi)容的解決方法
這篇文章主要介紹了iOS11 SectionHeader 胡亂移動(dòng)且滑動(dòng)時(shí)出現(xiàn)重復(fù)內(nèi)容的解決方法,需要的朋友可以參考下2017-11-11
searchDisplayController 引起的數(shù)組越界處理辦法
這篇文章主要介紹了searchDisplayController 引起的數(shù)組越界處理辦法,需要的朋友可以參考下2015-07-07

