简体   繁体   English

Alamofire:文件下载和验证失败

[英]Alamofire: file download and validation failure

In my iOS project I'm using Alamofire library to download remote documents (from a server with Basic Auth) in this way: 在我的iOS项目中,我使用Alamofire库以这种方式下载远程文档(来自具有Basic Auth的服务器):

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. 该文件已正确下载到应用程序的Documents文件夹中。

My problem is when user or/and password are wrong. 我的问题是user或/和password错误。 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. 在这种情况下,服务器响应状态是401 Unauthorized.validate()方法正确失败,但在我的Documents文件夹中,我找到文件“foo.pdf”,其中内容是一个解释401错误的xml。 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? 我的问题:Alamofire有没有办法保存文件,以防万一回复得到验证? 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: 编辑1:

It seems this issue quite some time ago brought this behaviour https://github.com/Alamofire/Alamofire/issues/233 很久以前这个问题似乎带来了这种行为https://github.com/Alamofire/Alamofire/issues/233

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM