【问题标题】:Allow to overwrite file using alamofire允许使用 alamofire 覆盖文件
【发布时间】:2015-02-02 19:13:54
【问题描述】:

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

可选(错误域=NSCocoaErrorDomain Code=516 "操作 无法完成。 (可可错误 516。)“用户信息 = 0x1740feb80 {NSSourceFilePathErrorKey=/private/var/mobile/Containers/Data/Application/B2674ABD-95F1-42AF-9F79-FE21F2929E14/tmp/CFNetworkDownload_1b6ZK8.tmp, NSUserStringVariant=( 移动),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

}

【问题讨论】:

    标签: ios swift alamofire


    【解决方案1】:

    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 类型。

    【讨论】:

    • 如果下载失败,那么我们最终将没有文件而不是过时的文件。这可能并不总是期望的。
    【解决方案2】:

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-24
      • 2021-09-21
      • 2011-11-25
      • 2016-09-05
      • 2021-06-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多