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

前面写过一篇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截图

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...