Rashad.Z
Rashad.Z

Reputation: 2604

Error When Copying A File in The Documents Directory To a Directory Within The Documents Directory

I am trying to copy a file in the documents directory to a directory within the documents directory but i am getting an error couldn’t be copied to “Documents” because an item with the same name already exists.

Any help would be appreciated.

Here is my code:

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

Upvotes: 3

Views: 4509

Answers (1)

djromero
djromero

Reputation: 19641

There's more than one way to do it. The simplest one would be to remove the destination file before copying it:

try! NSFileManager.removeItemAtURL(dstURL)

You may want to handle all the file management errors in a single place by implementing NSFileManagerDelegate:

  • Set NSFileManager().delegate to your class (where you're copying the file)
  • Intercept the error implementing one of the delegate methods. Depending on the error you can do different stuff to recover. Return true to continue or false to abort.

Example:

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

Upvotes: 5

Related Questions