我正在从URL下载Excel,然后尝试将Excel文件复制到本地临时文件中。临时文件路径每次都是唯一的,因为临时目录提供了基于UUID字符串的唯一路径。例如:第一次的路径是:文件:///private/var/mobile/Containers/Data/Application/FCA022DB-3B65-499E-9F91-190E307285B0/tmp/WindData.csv。第二次路径不同:/ private / var / mobile /容器/数据/应用程序/6CB02402-837D-4952-8C56-58572705B0AD/tmp/WindData.csv。
但是即使路径是唯一的,第二次出现错误“文件存在”。因此,通过FileManager.default.fileExists检查该文件是否存在,如果发现为true,则删除文件路径。此检查返回的错误就好像文件不存在一样,但是在下一行中,当我尝试将目标文件复制到目标Url时(因为它在上一行中不存在),它给出了错误消息:“错误:错误域= NSCocoaErrorDomain代码= 516”“ CFNetworkDownload_oHoanb.tmp“无法复制到” tmp“,因为已经存在具有相同名称的项目。” UserInfo = {NSSourceFilePathErrorKey = / private / var / mobile / Containers /数据/应用程序/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 {Error Domain = NSPOSIXErrorDomain Code = 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
}
您犯了一个非常常见的错误:
路径是path
,而不是absoluteString
if FileManager.default.fileExists(atPath: targetUrl.path) {
并且没有理由在Swift中使用NSURL
let tempDirectoryURL = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)