【问题标题】:Error When Copying A File in The Documents Directory To a Directory Within The Documents Directory将文档目录中的文件复制到文档目录中的目录时出错
【发布时间】:2015-12-07 09:07:25
【问题描述】:

我正在尝试将文档目录中的文件复制到文档目录中的目录,但我收到错误无法复制到“文档”,因为已经有同名项目存在。

任何帮助将不胜感激。

这是我的代码:

let documentsPath = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0])
        let logsPath = documentsPath.URLByAppendingPathComponent("Logs")


        let fileURL = documentsPath.URLByAppendingPathComponent("Database.db")

        do {
            try       NSFileManager.defaultManager().copyItemAtURL(fileURL, toURL: logsPath)
        } catch  let error1 as NSError{
            RZLog.Error ("Error:  \(error1.localizedDescription)")
        }

【问题讨论】:

    标签: ios nsfilemanager


    【解决方案1】:

    有不止一种方法可以做到这一点。 最简单的方法是在复制之前删除目标文件:

    try! NSFileManager.removeItemAtURL(dstURL)
    

    您可能希望通过实现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)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-24
      • 1970-01-01
      相关资源
      最近更新 更多