加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift 网络----利用URLSession的delegate模式下载多张图片

发布时间:2020-12-14 06:12:46 所属栏目:百科 来源:网络整理
导读:前面写过一篇swift 网络----利用URLSession的Block模式下载多张图片,主要界面的cell同上,本篇直接贴URLSession的delegate模式下封装好的网络库代码。 下载类 import Foundationimport UIKit//定义一个传图片数据的闭包public typealias SwiftClosure = ((_

前面写过一篇swift 网络----利用URLSession的Block模式下载多张图片,主要界面的cell同上,本篇直接贴URLSession的delegate模式下封装好的网络库代码。

下载类

import Foundation
import UIKit
//定义一个传图片数据的闭包
public typealias SwiftClosure = ((_ data:Data?,_ error: Error?) -> Void)

class LJSessionRequestManager: NSObject{
    
    /**
     *  定义闭包属性,可选类型
     */
    public  var callBackClosure : SwiftClosure?

    func sessoinDownload(_ url: String,_ method : String,_ callback: @escaping SwiftClosure)
    {
        callBackClosure = callback
        
        //1、创建URL下载地址
        let url:URL! = URL(string:url);
        
        //2、创建Request对象
        var urlRequest:URLRequest = URLRequest(url:url);
        urlRequest.httpMethod = method
        
        //3、创建会话
        let config = URLSessionConfiguration.default
        let session  = URLSession(configuration: config,delegate:self,delegateQueue: nil)

        //4、下载任务
        let downloadTask = session.downloadTask(with: urlRequest)
        
        //5、启动任务
        downloadTask.resume()
    }
    
    //初始化一个data,用来存储下载下来的数据
    private var _responseData: NSMutableData!
    var responseData: NSMutableData!{
        get{
            if _responseData == nil {
                _responseData = NSMutableData()
            }
            return _responseData
        }
        set{
            self._responseData = newValue
        }
    }
}


// MARK -  URLSessionDownloadDelegate
extension LJSessionRequestManager:URLSessionDownloadDelegate{
    
    //下载进度
    func urlSession(_ session: URLSession,downloadTask: URLSessionDownloadTask,didWriteData bytesWritten: Int64,totalBytesWritten: Int64,totalBytesExpectedToWrite: Int64) {
        
        //获取进度
        let written:CGFloat = CGFloat(bytesWritten)
        let total:CGFloat = CGFloat(totalBytesWritten)
        let pro:CGFloat = written/total
        print("----下载进度:------(pro)");
    }
    
    //下载偏移
    func urlSession(_ session: URLSession,didResumeAtOffset fileOffset: Int64,expectedTotalBytes: Int64) {
        //主要用于暂停续传
    }
    
    //下载结束
    func urlSession(_ session: URLSession,didFinishDownloadingTo location: URL) {
        //根据下载存储的location位置来获取data数据
        let data = (try? Data(contentsOf: URL(fileURLWithPath: location.path)))
        if callBackClosure != nil,let data = data{
            callBackClosure!(data,nil)
        }
        /*  保存到相册
            UIImage * image = [UIImage imageWithData:data];
            UIImageWriteToSavedPhotosAlbum(image,nil,nil);
         */
    }
    
     public func urlSession(_ session: URLSession,task: URLSessionTask,didCompleteWithError error: Error?)
     {
        if error != nil  {
            callBackClosure!(nil,error)
        }
     }
}

使用
 /* Session 的delegate模式下载图片或者数据*/
        LJTask = LJSessionRequestManager()
        LJTask?.sessoinDownload(imageUrlStr,"GET",{ (data,error)in
            
            //print(names!,ages!)
            //此处如果data有值的话,才去初始化image
            if error == nil,data != nil {
                let newImage = UIImage(data: data! as Data)
                let  titleImage = UIImageView(frame: CGRect(x: 0,y: 5,width: 40,height: 40))
                titleImage.image = newImage
                self.contentView.addSubview(titleImage)
            }
            else
            {
               print(error ?? "")
            }
        })

demo截图

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读