服务器之家

服务器之家 > 正文

详解Swift 利用Opration和OprationQueue来下载网络图片

时间:2021-03-29 15:35     来源/作者:水桶前辈

详解Swift 利用Opration和OprationQueue来下载网络图片

1. 基于Opration封装的获取网络数据组件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
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封装的网络数据管理组件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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. 此处下载一张图片

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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 ?? "")
    }
  })
}

 

详解Swift 利用Opration和OprationQueue来下载网络图片

如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

原文链接:http://blog.csdn.net/robinson_911/article/details/74853314

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
Intellij idea2020永久破解,亲测可用!!!
Intellij idea2020永久破解,亲测可用!!! 2020-07-29
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
返回顶部