欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2023-12-18 15:17:52
详解swift 利用opration和oprationqueue来下载网络图片 1. 基于opration封装的获取网络数据组件 import founda...

详解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 ?? "") 
    } 
  }) 
} 

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

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

上一篇:

下一篇: