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 }