5

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

可选(错误域=NSCocoaErrorDomain Code=516“操作无法完成。(Cocoa 错误 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 "操作无法完成。文件存在"})

我怎样才能告诉 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

}
4

2 回答 2

19

return-ing之前finalPath,使用 . 检查并删除该路径中的任何现有文件NSFileManager

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

在 Swift 3 中是这样的

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

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

其中 finalPath 是 URL 类型。

于 2014-12-05T08:22:08.427 回答
7

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

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

于 2017-05-23T23:25:10.317 回答