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

一、说明

NSURLSession是OC中的会话类,在Swift中变成URLSession类,它们的实现方式是一样的,下面的示例就Swift语法进行讲解和介绍。

二、介绍:

URLSession 类支持3种类型的任务:加载数据、下载和上传。

加载数据:Data Task

下载数据:Download Task

上传数据:Upload Task

毫无疑问,Session Task是整个URLSession架构的核心目标。

三。 下载 数据:Download Task

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

1. URLSession的URLSessionDownloadDelegate模式下载网络封装

import Foundation
import UIKit

public typealias SwiftClosure = ((_ data:Data? , _ progressValue:Float, _ 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
        
        //不需要缓存
        urlRequest.cachePolicy = .reloadIgnoringLocalCacheData
        
        //3、创建会话
        let config = URLSessionConfiguration.default
        let session  = URLSession(configuration: config, delegate:self, delegateQueue: nil)

        //4、下载任务  -- URLSessionDownloadDelegate 模式
        let loadDataTask = session.downloadTask(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 -  URLSessionDownloadDelegate   URLSessionDataDelegate  URLSessionDownloadDelegate
extension LJSessionRequestManager:URLSessionDownloadDelegate{
    
    //下载进度
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
        
        let  currentBytes :CGFloat = CGFloat(totalBytesWritten)
        let  allTotalBytes :CGFloat = CGFloat(totalBytesExpectedToWrite)
        
        //获取进度
        let proValue :Float = (Float)(currentBytes/allTotalBytes)
        print("----下载进度:------\(proValue*100)%");
        
        weak var weakSelf : LJSessionRequestManager? = self
        DispatchQueue.main.async
            {
                //将接收的数据结果回调到前台,用于进度展示
                weakSelf?.callBackClosure!(nil ,proValue ,nil)
        }
    }
    
    //下载偏移
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
        //主要用于暂停续传
    }
    
    //下载结束
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
        //根据下载存储的location位置来获取data数据
        let data = (try? Data(contentsOf: URL(fileURLWithPath: location.path)))
        if callBackClosure != nil ,let data = data{
            
            weak var weakSelf : LJSessionRequestManager? = self
            DispatchQueue.main.async
                {
                    //将接收的数据结果回调到前台,用于进度展示
                    weakSelf?.callBackClosure!(data ,1.0 ,nil)
            }
        }
        /*  保存到相册
         UIImage * image = [UIImage imageWithData:data];
         UIImageWriteToSavedPhotosAlbum(image, nil,nil,nil);
         */
    }
    
    public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)
    {
        if error != nil  {
            callBackClosure!(nil , 0, error)
        }
    }
}



2. 下面的demo界面UI

 /* 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截图


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值