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

前端之家收集整理的这篇文章主要介绍了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截图

猜你在找的Swift相关文章