Alamofire download issue(AlamoFire下载问题)
问题描述
我正在尝试使用带有Xcode 8.0和SWIFT 3.0的AlamoFire 4.0.0在我的代码中下载this picture。
这是我的请求:
func download(_ path: String, _ completionHandler: @escaping (Any?) -> ()) {
let stringURL = "https://slove.tulleb.com/uploads/6/6/0/2/66027561/2791411.jpg-1447979839.png"
print("Requesting (stringURL)...")
_ = Alamofire.download(stringURL)
.responseData { response in
print(response)
if let data = response.result.value {
completionHandler(UIImage(data: data))
} else {
completionHandler(nil)
}
}
}
我从服务器得到以下答案:
故障: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.inputFileReadFailed(file:/private/var/mobile/Containers/Data/Application/50400F41-47FD-4276-8903-F48D942D064A/tmp/CFNetworkDownload_D1Aqkh.tmp))
我不知道如何解决这个问题.是Alamofire的新版本有问题,还是我在什么地方忘了什么?
谢谢!
推荐答案
Official answer from cnoon (Alamofire member):
Hi@Tulleb,
很抱歉没有早点给你回复。示例@katopz是 不是同一类型的请求。该示例演示如何使用 数据任务,而不是下载任务。如果您不想下载 文件,您可以改为执行以下操作:
但是,为了回答您最初的问题,您遇到了沙箱权限问题。我们允许您使用 下载API,但不指定用于操作的目标闭包 像MacOS这样的系统,您可以在其中访问您自己的外部文件 沙盒。但是,在iOS上,您不能直接访问 您的沙箱之外的文件。这就是为什么你会看到 .inputFileReadFailed错误。Alamofire.request(url).responseData { response in guard let data = response.result.value else { return } let image = UIImage(data: data) print(image) }
有几种方法可以解决此问题。
选项1
您可以使用上面所示的请求API下载数据, 将图像数据下载到内存中,而不是下载到磁盘中。
选项2
您可以在访问数据之前将文件移动到沙箱中 使用目的地闭包。以下是如何做到这一点的示例:let destination: DownloadRequest.DownloadFileDestination = { _, _ in let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] let documentsURL = URL(fileURLWithPath: documentsPath, isDirectory: true) let fileURL = documentsURL.appendingPathComponent("image.png") return (fileURL, [.removePreviousFile, .createIntermediateDirectories]) } Alamofire.download("https://httpbin.org/image/png", to: destination).responseData { response in debugPrint(response) if let data = response.result.value { let image = UIImage(data: data) print(image) } else { print("Data was invalid") } }
//输出:
//[请求]:https://httpbin.org/image/png//[响应]: {URL:https://httpbin.org/image/png }{状态码:200,标题{//"Access-Control-Allow-Origin"= "*";//"Content-Length"=8090;//"Content-Type"= "image/png";//date="星期六,2016年9月24日21:34:25 GMT";//
server=nginx;//"Access-Control-Allow-Credentials"=true;/
本文标题为:AlamoFire下载问题


- android 4中的android RadioButton问题 2022-01-01
- Android - 拆分 Drawable 2022-01-01
- 如何检查发送到 Android 应用程序的 Firebase 消息的传递状态? 2022-01-01
- 想使用ViewPager,无法识别android.support.*? 2022-01-01
- Android viewpager检测滑动超出范围 2022-01-01
- 使用自定义动画时在 iOS9 上忽略 edgesForExtendedLayout 2022-01-01
- Android - 我如何找出用户有多少未读电子邮件? 2022-01-01
- 在测试浓缩咖啡时,Android设备不会在屏幕上启动活动 2022-01-01
- MalformedJsonException:在第1行第1列路径中使用JsonReader.setLenient(True)接受格式错误的JSON 2022-01-01
- 用 Swift 实现 UITextFieldDelegate 2022-01-01