Ios 允许使用alamofire覆盖文件

Ios 允许使用alamofire覆盖文件,ios,swift,alamofire,Ios,Swift,Alamofire,我正在使用alamofire下载一个PDF文件。它基本上可以工作,但是当多次下载时,iOS似乎不会覆盖文件。我得到这个错误: 可选(错误域=NSCOCAERRORDOMAIN代码=516“操作 无法完成。(可可错误516。)“UserInfo=0x1740feb80 {NSSourceFilePathErrorKey=/private/var/mobile/Containers/Data/Application/B2674ABD-95F1-42AF-9F79-fe21f29e14/tmp/CFN

我正在使用alamofire下载一个PDF文件。它基本上可以工作,但是当多次下载时,iOS似乎不会覆盖文件。我得到这个错误:

可选(错误域=NSCOCAERRORDOMAIN代码=516“操作 无法完成。(可可错误516。)“UserInfo=0x1740feb80 {NSSourceFilePathErrorKey=/private/var/mobile/Containers/Data/Application/B2674ABD-95F1-42AF-9F79-fe21f29e14/tmp/CFNetworkDownload_1b6ZK8.tmp, NSUserStringVariant=( Move),NSDestinationFilePath=/var/mobile/Containers/Data/Application/B2674ABD-95F1-42AF-9F79-fe21f299e14/Documents/11月 2014.pdf,NSFilePath=/private/var/mobile/Containers/Data/Application/B2674ABD-95F1-42AF-9F79-fe21f29e14/tmp/CFNetworkDownload_1b6ZK8.tmp, NSUnderlyingError=0x17405fb00“该操作无法完成。 文件存在“})

我如何告诉alamofire覆盖该文件?我的代码:

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

}

返回
-ing
最终路径
之前,请使用
NSFileManager
检查并删除该路径上的任何现有文件

if NSFileManager.defaultManager().fileExistsAtPath(finalPath) {
    NSFileManager.defaultManager().removeItemAtPath(finalPath, error: nil)
}
斯威夫特3就是这样

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

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

其中finalPath是URL类型。

DownloadFileDestination
闭包中,您可以如下设置
removePreviousFile

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

来源:

如果下载失败,我们将没有文件,而不是过时的文件。这可能并不总是人们的期望。