Copying remote file to temporary ios File gives error: File Exists

Copying remote file to temporary ios File gives error: File Exists

我正在从 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

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

"Error: Error Domain=NSCocoaErrorDomain Code=516 "“CFNetworkDownload_oHoanb.tmp” couldn’t be copied to “tmp” because an item with the same name already exists." UserInfo={NSSourceFilePathErrorKey=/private/var/mobile/Containers/Data/Application/DB863D34-3F66-45C8-B129-76DB6FC61D0E/tmp/CFNetworkDownload_oHoanb.tmp, NSUserStringVariant=( Copy ), 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 {Error Domain=NSPOSIXErrorDomain Code=17 "File exists"}}"

如何解决这个问题?

 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
}

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

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

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

并且没有理由在Swift

中使用NSURL
let tempDirectoryURL = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)