Alamofire: Download request saves error response as original file even when validation fails

Viewed 480

I use Alamofire 4.5.1 to download some mp3 files.

If I provide incorrect URL or the request can't be authorised I get an error with 4xx status code (as it is supposed to be) and in my particular case xml with the error explanation.

The issue is that Alamofire saves the error xml response to my destination url, which looks like: .../my-sound-file.mp3

In other place in my app, which is decoupled from downloading code, I might later check if I have .../my-sound-file.mp3 on disk and try to play it, which obviously fails since my sound file is actually xml file with mp3 extension.

Is there a nicer way to prevent Alamofire saving an error data as an originally requested file?

The code I use (with my crude solution to this issue):

let destination: DownloadRequest.DownloadFileDestination = ...

let request = self.sessionManager.download(url, to: destination)
request.validate()
request.response { response in
    if  response.error == nil {
        // do some stuff
    } else {
        // So far I am forced to manually remove file in case of error
        try? FileManager.default.removeItem(at: destURL)
        // propagate error
    }
}

I stumbled upon this because I assumed that if a request validation fails the destination URL should be empty.

I think I am not the only one with this assumption: Alamofire: file download and validation failure

1 Answers

Personally, I delete the file in case of error. Just as you propose.

Related