Alamofire支持下载图片到内存或者磁盘,Alamofire.request开头的请求会把数据加载进内存,适用于小文件,如果文件比较大,可能会造成内存溢出.因此如果文件比较大,应该是Alamofire.download方法,把数据临时的保存在磁盘中,该方法同时还支持后台下载. 例如
Alamofire.download("https://httpbin.org/image/png").responseData { response in
if let data = response.result.value {
let image = UIImage(data: data)
}
}
框架提供了DownloadFileDestination,来允许自定义destinationURL,DownloadOptions这两个属性,如果不指定Destination,文件将被下载到temporaryURL.我们来看看这个闭包的结构
public typealias DownloadFileDestination = (
_ temporaryURL: URL,
_ response: HTTPURLResponse)
-> (destinationURL: URL, options: DownloadOptions)
//options包含的枚举
.createIntermediateDirectories//根据路径来创建文件夹
.removePreviousFile//移除当前路径的旧文件
通过例子来试一下
let destination: DownloadRequest.DownloadFileDestination = { _, _ in
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let fileURL = documentsURL.appendingPathComponent("pig.png")
return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}
Alamofire.download("https://httpbin.org/image/png", to: destination).response { response in
print(response)
if response.error == nil, let imagePath = response.destinationURL?.path {
let image = UIImage(contentsOfFile: imagePath)
}
}
在制定路径下顺利拿到图片
Alamofire也提供了建议的destination设置
let destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory)
Alamofire.download("https://httpbin.org/image/png", to: destination)
下载进度
任何Alamofire.download方法都可以通过downloadProgress获取下载进度
Alamofire.download("https://cdn.pixabay.com/photo/2017/06/26/12/49/red-wine-2443699_1280.jpg")
.downloadProgress { progress in
print("Download Progress: \(progress.fractionCompleted)")
}
.responseData { response in
if let data = response.result.value {
let image = UIImage(data: data)
}
}
downloadProgress支持自定义queue
let utilityQueue = DispatchQueue.global(qos: .utility)
Alamofire.download("https://httpbin.org/image/png")
.downloadProgress(queue: utilityQueue) { progress in
print("Download Progress: \(progress.fractionCompleted)")
}
.responseData { response in
if let data = response.result.value {
let image = UIImage(data: data)
}
}
如果DownloadRequest被取消或者被中断,response会包含一个resumeData,可以用来重新发起请求.
class ImageRequestor {
private var resumeData: Data?
private var image: UIImage?
func fetchImage(completion: (UIImage?) -> Void) {
guard image == nil else { completion(image) ; return }
let destination: DownloadRequest.DownloadFileDestination = { _, _ in
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let fileURL = documentsURL.appendingPathComponent("pig.png")
return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}
let request: DownloadRequest
if let resumeData = resumeData {
request = Alamofire.download(resumingWith: resumeData)
} else {
request = Alamofire.download("https://httpbin.org/image/png")
}
request.responseData { response in
switch response.result {
case .success(let data):
self.image = UIImage(data: data)
case .failure:
self.resumeData = response.resumeData
}
}
}
}
上传数据
- Alamofire.request//上传小数据(JSON,URL编码参数)
- Alamofire.upload //上传大数据或者数据流(支持后台上传) Alamofire可以通过下列方式上传数据
- Data
- fileURL
- inputStream
- MultipartFormData
Data上传
let imageData = UIPNGRepresentation(image)!
Alamofire.upload(imageData, to: "https://httpbin.org/post").responseJSON { response in
debugPrint(response)
}
通过路径上传
let imageData = UIPNGRepresentation(image)!
Alamofire.upload(imageData, to: "https://httpbin.org/post").responseJSON { response in
debugPrint(response)
}
Multipart Form Data
Alamofire.upload(
//通过 multipartFormData.append拼接,参数是获取数据的方式和数据名称
multipartFormData: { multipartFormData in
multipartFormData.append(unicornImageURL, withName: "unicorn")
multipartFormData.append(rainbowImageURL, withName: "rainbow")
},
to: "https://httpbin.org/post",
//要上传的数据编码后的回调
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
//如果是成功的,那么它会返回一个UploadRequest
upload.responseJSON { response in
debugPrint(response)
}
case .failure(let encodingError):
print(encodingError)
}
}
)
上传进度
let fileURL = Bundle.main.url(forResource: "video", withExtension: "mov")
Alamofire.upload(fileURL, to: "https://httpbin.org/post")
.uploadProgress { progress in // main queue by default
print("Upload Progress: \(progress.fractionCompleted)")
}
.downloadProgress { progress in // main queue by default
print("Download Progress: \(progress.fractionCompleted)")
}
.responseJSON { response in
debugPrint(response)
}