2015-12-07 145 views
0

我試圖將文檔目錄中的文件複製到文檔目錄內的目錄,但出現錯誤無法複製到「文件」,因爲具有相同名稱的項目已經存在。將文檔目錄中的文件複製到文檔目錄中的目錄時出錯

任何幫助,將不勝感激。

這裏是我的代碼:

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)") 
     } 
+0

沒有人幫忙? –

回答

2

不止一種方法去做一件事。 最簡單的一種是在複製之前刪除目標文件:

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) 
    } 
}