Alamofire iOS - specify during-download location that isn't temp directory

390 Views Asked by At

I know that Alamofire (iOS) allows the specification of a download destination, but the file stays in the temp directory until the download is complete. We want to be able to have the file sit in the Documents Directory during this process (and have the download remain there once it's complete).

Does anyone know if this is possible?

Thanks

2

There are 2 best solutions below

0
On BEST ANSWER

I wasn't able to accomplish this with download tasks. Alamofire essentially wraps URLSession, and Alamofire.download wraps URLSessionDownloadTask, and I'd already tried using this outside of Alamofire. The file isn't placed in your download destination until it's complete.

To accomplish this for now, I've had to use a URLSessionDataTask, and write the data chunk by chunk to a file using am OutputStream/NSOutputStream that is opened and closed repeatedly, so that it gets flushed, and can be read before it is complete. That's what I was trying to accomplish, and it appears to work, and work more than fast enough.

1
On

Yes, specify the download location URL

let destination: DownloadRequest.DownloadFileDestination = { _, _ in
    let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
    let fileURL = documentsURL.appendPathComponent("pig.png")

    return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}

Alamofire.download(urlString, to: destination).response { response in
    print(response)

    if response.result.isSuccess, let imagePath = response.destinationURL?.path {
        let image = UIImage(contentsOfFile: imagePath)
    }
}

Change the document directory Path as you require.