Alamofire:文件下载和验证失败 [英] Alamofire: file download and validation failure

查看:331
本文介绍了Alamofire:文件下载和验证失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的iOS项目中,我正在使用 Alamofire 库以这种方式(从具有Basic Auth的服务器上)下载远程文档:

 放置目标位置:DownloadRequest.DownloadFileDestination = {_,
中的_让documentsURL = FileManager.default.urls(for:.documentDirectory,in:.userDomainMask )[0]
让fileURL = documentsURL.appendingPathComponent( foo.pdf)
返回(filePath.url,[.removePreviousFile,.createIntermediateDirectories])
}

Alamofire.download(myUrlRequest,to:destination).authenticate(user:user,password:password,persistence:.none).validate()。response {响应
打印(response)
if response.error == nil,让path = response.destinationURL?.path {
print(path)
}
}

这很好用!该文件已正确下载到应用程序的Documents文件夹中。



我的问题是当 user 或/和密码错误。在这种情况下,服务器响应状态为 401未经授权 .validate()方法正确失败,但是在我的Documents文件夹中找到文件 foo.pdf,其中的内容是解释 401 错误的xml。我想要的是仅在验证没有失败的情况下保存文件。



我的问题:Alamofire是否有办法保存文件以防万一响应得到验证?还是在验证失败时必须手动删除文件?

解决方案

我现在遇到类似的问题。到目前为止,我唯一能想到的就是粗糙的

  if response.error!= nil {
试试吗? FileManager.default.removeItem(at:destinationURL)
}

。 p>

我将进一步调查。



编辑1:



似乎很早以前这个问题带来了这种行为 https://github.com/Alamofire / Alamofire / issues / 233


In my iOS project I'm using Alamofire library to download remote documents (from a server with Basic Auth) in this way:

let destination: DownloadRequest.DownloadFileDestination = { _, _ in
    let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
    let fileURL = documentsURL.appendingPathComponent("foo.pdf")
    return (filePath.url, [.removePreviousFile, .createIntermediateDirectories])
}

Alamofire.download(myUrlRequest, to: destination).authenticate(user: user, password: password, persistence: .none).validate().response { response in
    print(response)
    if response.error == nil, let path = response.destinationURL?.path {
        print(path)
    }
}

This works great! The file is correctly downloaded in the app's Documents folder.

My problem is when user or/and password are wrong. In this case server response status is 401 Unauthorized and .validate() method correctly fails, but in my Documents folder I find the file "foo.pdf" where the content is a xml that explains the 401 error. What I would like is the file saved only if the validate doesn't fail.

My questions: is there a way, with Alamofire, to save the file just in case the response is validated? Or do I have to manually delete the file when validate fails?

解决方案

I am having the similar issue at the moment. So far, the only thing I could think of is crude

if response.error != nil {
    try? FileManager.default.removeItem(at: destinationURL)
}

in response closure.

I will investigate further though.

EDIT 1:

It seems this issue quite some time ago brought this behaviour https://github.com/Alamofire/Alamofire/issues/233

这篇关于Alamofire:文件下载和验证失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆