Alamofire: file download and validation failure

徘徊边缘 提交于 2019-12-10 18:07:34

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/45235316/alamofire-file-download-and-validation-failure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!