Allow overwrite file with alamofire

I am downloading a pdf file using alamofire. This basically works, however iOS doesn't seem to overwrite the file when downloading is done several times. I get this error:

Optional (Error Domain = NSCocoaErrorDomain Code = 516 "The operation could not be completed. (Cocoa error 516.)" UserInfo = 0x1740feb80 {NSSourceFilePathErrorKey = / private / var / mobile / Containers / data / Application / B2674ABD-95F1-42AF-929914-FE29F21 /TMP/CFNetworkDownload_1b6ZK8.tmp, NSUserStringVariant = (Move), NSDestinationFilePath = / var / mobile / Containers / Data / Application / B2674ABD-95F1-42AF-9F79-FE21F2929E14 / Documents / November 2014.pdf / NSFPP private mobile / Containers / Data / Application / B2674ABD-95F1-42AF-9F79-FE21F2929E14 / tmp / CFNetworkDownload_1b6ZK8.tmp, NSUnderlyingError = 0x17405fb00 "The operation cannot be completed. The file exists"})

How can I tell alamofire to overwrite a file? My code is:

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 } 
+5
source share
2 answers

Prior to return -ing finalPath check and delete any existing file in this path using NSFileManager .

 if NSFileManager.defaultManager().fileExistsAtPath(finalPath) { NSFileManager.defaultManager().removeItemAtPath(finalPath, error: nil) } 

I like it so much in Swift 3

 if FileManager.default.fileExists(atPath: finalPath.path) { do{ try FileManager.default.removeItem(atPath: finalPath.path) }catch{ print("Handle Exception") } } 

Where finalPath is the type of URL.

+19
source

In closing DownloadFileDestination you can set removePreviousFile as follows:

 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

+3
source

Source: https://habr.com/ru/post/1208378/


All Articles