2014-12-04 12 views
5

Ich lade eine PDF-Datei mit Alamofire. Es funktioniert grundsätzlich, aber iOS scheint die Datei nicht zu überschreiben, wenn der Download mehrmals durchgeführt wird. Ich erhalte diesen Fehler:Lassen Sie die Datei mit alamofire überschreiben

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"})

Wie kann ich alamofire sagen, die Datei zu überschreiben? Mein 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 

} 

Antwort

19

Vor return -ing finalPath, für überprüfen und entfernen Sie eine vorhandene Datei in diesem Pfad NSFileManager.

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

In Swift 3 es ist wie die

if FileManager.default.fileExists(atPath: finalPath.path) { 

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

Wo finalPath URL-Typ ist.

+0

Wenn der Download fehlschlägt, dann werden wir ohne Datei am Ende statt einer veralteten Datei. Das ist vielleicht nicht immer die Erwartung. –

3

Im DownloadFileDestination Verschluss, können Sie removePreviousFile wie folgt festgelegt:

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) 
    } 
} 

Quelle: https://github.com/Alamofire/Alamofire#download-file-destination

Verwandte Themen