Alamofire4.x开源代码分析(三)文件上传下载

Alamofire支持下载图片到内存或者磁盘,Alamofire.request开头的请求会把数据加载进内存,适用于小文件,如果文件比较大,可能会造成内存溢出.因此如果文件比较大,应该是Alamofire.download方法,把数据临时的保存在磁盘中,该方法同时还支持后台下载. 例如

1Alamofire.download("https://httpbin.org/image/png").responseData { response in 2 if let data = response.result.value { 3 let image = UIImage(data: data) 4 } 5}

框架提供了DownloadFileDestination,来允许自定义destinationURL,DownloadOptions这两个属性,如果不指定Destination,文件将被下载到temporaryURL.我们来看看这个闭包的结构

1public typealias DownloadFileDestination = ( 2 _ temporaryURL: URL, 3 _ response: HTTPURLResponse) 4 -> (destinationURL: URL, options: DownloadOptions) 5 //options包含的枚举 6 .createIntermediateDirectories//根据路径来创建文件夹 7 .removePreviousFile//移除当前路径的旧文件

通过例子来试一下

1 let destination: DownloadRequest.DownloadFileDestination = { _, _ in 2 let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] 3 let fileURL = documentsURL.appendingPathComponent("pig.png") 4 5 return (fileURL, [.removePreviousFile, .createIntermediateDirectories]) 6 } 7 8 Alamofire.download("https://httpbin.org/image/png", to: destination).response { response in 9 print(response) 10 11 if response.error == nil, let imagePath = response.destinationURL?.path { 12 let image = UIImage(contentsOfFile: imagePath) 13 } 14 } 15

在制定路径下顺利拿到图片

Alamofire也提供了建议的destination设置

1let destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory) 2Alamofire.download("https://httpbin.org/image/png", to: destination)

下载进度

任何Alamofire.download方法都可以通过downloadProgress获取下载进度

1 Alamofire.download("https://cdn.pixabay.com/photo/2017/06/26/12/49/red-wine-2443699_1280.jpg") 2 .downloadProgress { progress in 3 print("Download Progress: \(progress.fractionCompleted)") 4 } 5 .responseData { response in 6 if let data = response.result.value { 7 let image = UIImage(data: data) 8 } 9 }

downloadProgress支持自定义queue

1let utilityQueue = DispatchQueue.global(qos: .utility) 2 3Alamofire.download("https://httpbin.org/image/png") 4 .downloadProgress(queue: utilityQueue) { progress in 5 print("Download Progress: \(progress.fractionCompleted)") 6 } 7 .responseData { response in 8 if let data = response.result.value { 9 let image = UIImage(data: data) 10 } 11 }

如果DownloadRequest被取消或者被中断,response会包含一个resumeData,可以用来重新发起请求.

1class ImageRequestor { 2 private var resumeData: Data? 3 private var image: UIImage? 4 5 func fetchImage(completion: (UIImage?) -> Void) { 6 guard image == nil else { completion(image) ; return } 7 8 let destination: DownloadRequest.DownloadFileDestination = { _, _ in 9 let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] 10 let fileURL = documentsURL.appendingPathComponent("pig.png") 11 12 return (fileURL, [.removePreviousFile, .createIntermediateDirectories]) 13 } 14 15 let request: DownloadRequest 16 17 if let resumeData = resumeData { 18 request = Alamofire.download(resumingWith: resumeData) 19 } else { 20 request = Alamofire.download("https://httpbin.org/image/png") 21 } 22 23 request.responseData { response in 24 switch response.result { 25 case .success(let data): 26 self.image = UIImage(data: data) 27 case .failure: 28 self.resumeData = response.resumeData 29 } 30 } 31 } 32}

上传数据

  • Alamofire.request//上传小数据(JSON,URL编码参数)
  • Alamofire.upload //上传大数据或者数据流(支持后台上传) Alamofire可以通过下列方式上传数据
  • Data
  • fileURL
  • inputStream
  • MultipartFormData

Data上传

1let imageData = UIPNGRepresentation(image)! 2 3Alamofire.upload(imageData, to: "https://httpbin.org/post").responseJSON { response in 4 debugPrint(response) 5}

通过路径上传

1let imageData = UIPNGRepresentation(image)! 2 Alamofire.upload(imageData, to: "https://httpbin.org/post").responseJSON { response in 3 debugPrint(response) 4 }

Multipart Form Data

1Alamofire.upload( 2//通过 multipartFormData.append拼接,参数是获取数据的方式和数据名称 3 multipartFormData: { multipartFormData in 4 multipartFormData.append(unicornImageURL, withName: "unicorn") 5 multipartFormData.append(rainbowImageURL, withName: "rainbow") 6 }, 7 to: "https://httpbin.org/post", 8 //要上传的数据编码后的回调 9 encodingCompletion: { encodingResult in 10 switch encodingResult { 11 case .success(let upload, _, _): 12 //如果是成功的,那么它会返回一个UploadRequest 13 upload.responseJSON { response in 14 debugPrint(response) 15 } 16 case .failure(let encodingError): 17 print(encodingError) 18 } 19 } 20)

上传进度

1let fileURL = Bundle.main.url(forResource: "video", withExtension: "mov") 2 3Alamofire.upload(fileURL, to: "https://httpbin.org/post") 4 .uploadProgress { progress in // main queue by default 5 print("Upload Progress: \(progress.fractionCompleted)") 6 } 7 .downloadProgress { progress in // main queue by default 8 print("Download Progress: \(progress.fractionCompleted)") 9 } 10 .responseJSON { response in 11 debugPrint(response) 12 }
点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )

Alamofire4.x开源代码分析(三)文件上传下载 - HelloWorld