Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow to overwrite file using alamofire

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

}
like image 501
UpCat Avatar asked Dec 04 '14 19:12

UpCat


2 Answers

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.

like image 101
mattt Avatar answered Nov 12 '22 17:11

mattt


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

like image 7
Zia Avatar answered Nov 12 '22 17:11

Zia