I am downloading a PDF file using alamofire. It basically works however iOS does not seem to overwrite the file when the download is made multiple times. I get this error:
Optional(Error Domain=NSCocoaErrorDomain Code=516 "The operation couldn’t be completed. (Cocoa error 516.)" UserInfo=0x1740feb80 {NSSourceFilePathErrorKey=/private/var/mobile/Containers/Data/Application/B2674ABD-95F1-42AF-9F79-FE21F2929E14/tmp/CFNetworkDownload_1b6ZK8.tmp, NSUserStringVariant=( Move ), NSDestinationFilePath=/var/mobile/Containers/Data/Application/B2674ABD-95F1-42AF-9F79-FE21F2929E14/Documents/November 2014.pdf, NSFilePath=/private/var/mobile/Containers/Data/Application/B2674ABD-95F1-42AF-9F79-FE21F2929E14/tmp/CFNetworkDownload_1b6ZK8.tmp, NSUnderlyingError=0x17405fb00 "The operation couldn’t be completed. File exists"})
How can I tell alamofire to overwrite the file? My code:
var fileName = ""
var filePath = ""
Alamofire.manager.download(Router.listToPdf(), destination: { (temporaryURL, response) -> (NSURL) in
if let directoryURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as? NSURL {
fileName = response.suggestedFilename!
finalPath = directoryURL.URLByAppendingPathComponent(fileName!)
return finalPath!
}
return temporaryURL
}).response { (_, _, data, err) -> Void in
}
Before return
-ing finalPath
, check for and remove any existing file at that path using NSFileManager
.
if NSFileManager.defaultManager().fileExistsAtPath(finalPath) {
NSFileManager.defaultManager().removeItemAtPath(finalPath, error: nil)
}
In Swift 3 it's like that
if FileManager.default.fileExists(atPath: finalPath.path) {
do{
try FileManager.default.removeItem(atPath: finalPath.path)
}catch{
print("Handle Exception")
}
}
Where finalPath is URL type.
In the DownloadFileDestination
closure, you can set removePreviousFile
like this:
let destination: DownloadRequest.DownloadFileDestination = { _, _ in
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let fileURL = documentsURL.appendingPathComponent("pig.png")
return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}
Alamofire.download(urlString, to: destination).response { response in
print(response)
if response.error == nil, let imagePath = response.destinationURL?.path {
let image = UIImage(contentsOfFile: imagePath)
}
}
Source: https://github.com/Alamofire/Alamofire#download-file-destination
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With