将Alamofire的下载进度(completion handler)改写为async/await的方式,可以让代码更加简洁和易于理解。可以使用Swift 5.5的async/await特性,代码如下:
import Alamofire
func downloadFile(withURL url: URL) async throws -> Data {
let result = try await withUnsafeThrowingContinuation { (continuation: UnsafeContinuation) in
AF.download(url, to: .cachesDirectory)
.downloadProgress { progress in
print("Download progress: \(progress.fractionCompleted)")
}
.response { response in
if let data = response.fileContents {
continuation.resume(returning: data)
} else {
continuation.resume(throwing: NSError(domain: "Download Error", code: -1, userInfo: nil))
}
}
}
return result
}
在上面的代码中,我们首先使用async标志函数,并将其返回类型设置为Data类型。然后,我们使用withUnsafeThrowingContinuation函数创建一个不安全的continuation对象,该对象用于在下载完成时继续执行代码。接下来,我们使用Alamofire的download函数来执行真正的下载操作,并使用downloadProgress闭包实时更新下载进度。最后,我们使用response闭包处理下载的响应,并在下载成功时通过resume返回数据,或在下载失败时通过resume抛出错误。
上一篇:AlamofireDidFinishCollectingMetricsCrash
下一篇:Alamofire对Google Snap to Road API的调用返回nil作为响应,并显示Alamofire.AFError.invalidURL错误。