简体   繁体   中英

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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