且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Alamofire:文件下载和验证失败

更新时间:2022-10-17 17:45:45

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

  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