我正在尝试将文档目录中的文件复制到文档目录中的目录,但出现错误无法将\xe2\x80\x99t 复制到\xe2\x80\x9cDocuments\xe2\x80\x9d,因为带有同名已经存在。
\n\n任何帮助,将不胜感激。
\n\n这是我的代码:
\n\nlet documentsPath = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0])\n let logsPath = documentsPath.URLByAppendingPathComponent("Logs")\n\n\n let fileURL = documentsPath.URLByAppendingPathComponent("Database.db")\n\n do {\n try NSFileManager.defaultManager().copyItemAtURL(fileURL, toURL: logsPath)\n } catch let error1 as NSError{\n RZLog.Error ("Error: \\(error1.localizedDescription)")\n }\nRun Code Online (Sandbox Code Playgroud)\n
有不止一种方法可以做到这一点。最简单的方法是在复制之前删除目标文件:
try! NSFileManager.removeItemAtURL(dstURL)
Run Code Online (Sandbox Code Playgroud)
您可能希望通过实施以下方法在一个位置处理所有文件管理错误NSFileManagerDelegate:
NSFileManager().delegate为您的班级(您要复制文件的位置)true以继续或false中止。例子:
class AnyClass : NSFileManagerDelegate {
let fileManager = NSFileManager()
func fileManager(fileManager: NSFileManager, shouldProceedAfterError error: NSError, copyingItemAtURL srcURL: NSURL, toURL dstURL: NSURL) -> Bool {
if error.code == NSFileWriteFileExistsError {
try! fileManager.removeItemAtURL(dstURL)
copyFrom(srcURL, to: dstURL)
return true
} else {
return false
}
}
func copyFrom(a: NSURL, to b: NSURL) {
try! fileManager.copyItemAtURL(a, toURL: b)
}
func entryPoint() {
fileManager.delegate = self
copyFrom(sourceURL, to: destinationURL)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4189 次 |
| 最近记录: |