【问题标题】:Copying remote file to temporary ios File gives error: File Exists将远程文件复制到临时 ios 文件出现错误:文件存在
【发布时间】:2020-08-20 23:09:19
【问题描述】:

我正在从 URL 下载 Excel 文件并尝试将 Excel 文件复制到本地临时文件中。临时文件路径每次都是唯一的,因为临时目录提供了一个唯一的基于 UUID 字符串的路径。

比如第一次的路径是:

file:///private/var/mobile/Containers/Data/Application/FCA022DB-3B65-499E-9F91-190E307285B0/tmp/WindData.csv

第二次路径不同:

/private/var/mobile/Containers/Data/Application/6CB02402-837D-4952-8C56-58572705B0AD/tmp/WindData.csv

但我第二次收到错误“文件存在”,即使路径是唯一的。因此,通过 FileManager.default.fileExists 检查文件是否存在,如果发现为真,则删除文件路径。此检查返回错误,就好像文件不存在一样,但是在下一行当我尝试将目标文件复制到目标 Url 时(因为它在上一行中不存在),它给出了错误:

“错误:错误域=NSCocoaErrorDomain 代码=516 ““CFNetworkDownload_oHoanb.tmp”无法复制到“tmp”,因为 已存在同名项目。” UserInfo={NSSourceFilePathErrorKey=/private/var/mobile/Containers/Data/Application/DB863D34-3F66-45C8-B129-76DB6FC61D0E/tmp/CFNetworkDownload_oHoanb.tmp, NSUserStringVariant=( 复制),NSDestinationFilePath=/private/var/mobile/Containers/Data/Application/DB863D34-3F66-45C8-B129-76DB6FC61D0E/tmp/WindData.csv, NSFilePath=/private/var/mobile/Containers/Data/Application/DB863D34-3F66-45C8-B129-76DB6FC61D0E/tmp/CFNetworkDownload_oHoanb.tmp, NSUnderlyingError=0x2801e93b0 {错误域=NSPOSIXErrorDomain 代码=17 "文件存在"}}"

如何解决这个问题?

 let datadownloadTask = URLSession.shared.downloadTask(with: vendorURL!, completionHandler: { (responseUrl, response, error) in
        do {
            if let tempUrl = responseUrl {
                if let statusCode = (response as? HTTPURLResponse)?.statusCode {
                    print("Successfully downloaded. Status code: \(statusCode)")
                }

                do {
                    let targetUrl = self.copyResourcetoTempFile(sourceUrl: tempUrl, resourceName: "WindData", fileExtension: "csv")
                    if let destUrl = targetUrl {
                        let data = try String(contentsOfFile: destUrl.absoluteString!, encoding: .utf8)
                        let avg = self.parseCsv(data: data)
                        self.avg = avg
                    }

                } catch (let writeError) {
                    print("Error creating a file \(tempUrl) : \(writeError)")
                }

                completion(self.avg)
            }
        } catch {
            print("error: \(error.localizedDescription)")
        }
    })
    datadownloadTask.resume()
}

public func copyResourcetoTempFile(sourceUrl: URL, resourceName: String, fileExtension: String) -> NSURL?
{
    let tempDirectoryURL = NSURL.fileURL(withPath: NSTemporaryDirectory(), isDirectory: true)
    let targetUrl = tempDirectoryURL.appendingPathComponent(resourceName).appendingPathExtension(fileExtension)
    do {
        if FileManager.default.fileExists(atPath: targetUrl.absoluteString) {
           try FileManager.default.removeItem(at: targetUrl)
        }
        try FileManager.default.copyItem(at: sourceUrl, to: targetUrl)
        return targetUrl as NSURL
    } catch let error {
        NSLog("Error: \(error)")
    }
    return nil
}

【问题讨论】:

    标签: ios swift nsfilemanager


    【解决方案1】:

    你犯了一个很常见的错误:

    文件系统URL的路径path,而不是absoluteString,后者代表整个URL,包括方案。

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

    而且没有理由在 Swift 中使用NSURL

    let tempDirectoryURL = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
    

    【讨论】:

    • 感谢它现在有效。只是好奇 URL.pat 是否是正确的 URL.absoluteString 的目的是什么
    • 正如我所说,absoluteString 包括该方案(file://http:// 等)。有时你需要它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-18
    • 1970-01-01
    • 2011-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多