Search code examples
iosiphoneswift2nsfilemanagerxcode7

NSFileManager fileExistsAtPath unable to overwrite existing file in Swift 2


Hello I'm upgrading my existing code to Swift 2, and I need some help with the copy of a file inside the DocumentDirectoy.

This is converted code I'm using to check if the file exists, and if it does, we should copy it either way, but it keeps returning an error saying the file exists, which it is true, but we need to overwrite it.

func copyXMLFile()
    {
    // Get a reference for the Document directory
    let rootPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, .UserDomainMask, true)[0] 
    // Get a reference for the data.xml file
    xmlPathInDocument = rootPath.stringByAppendingString("data.xml")
    if NSFileManager.defaultManager().fileExistsAtPath(xmlPathInDocument){
        print("xml file exists")

                let xmlPathInBundle = NSBundle.mainBundle().pathForResource("data", ofType: "xml")!
        do {
            // copy file from main bundle to documents directory
            print("copy")
            try NSFileManager.defaultManager().copyItemAtPath(xmlPathInBundle, toPath: xmlPathInDocument)
        } catch let error as NSError {
            // Catch fires here, with an NSErrro being thrown
            print("error occurred, here are the details:\n \(error)")
        }
    }
    else
    {
        // copy the file either way

        let xmlPathInBundle = NSBundle.mainBundle().pathForResource("data", ofType: "xml")!
        do {
            // copy file from main bundle to documents directory
            print("copy")
            try NSFileManager.defaultManager().copyItemAtPath(xmlPathInBundle, toPath: xmlPathInDocument)
        } catch let error as NSError {
            // Catch fires here, with an NSErrro being thrown
            print("error occurred, here are the details:\n \(error)")
        }

    }

 }

error occurred, here are the details:

Error Domain=NSCocoaErrorDomain Code=516 "The operation couldn’t be completed. (Cocoa error 516.)" UserInfo=0x7a67b680 {NSSourceFilePathErrorKey=/Users/User1/Library/Developer/CoreSimulator/Devices/0E591E5B-2E2F-4CCB-9099-95CE1EA3F557/data/Containers/Bundle/Application/E3C8FAE4-703D-46CA-AC37-A1C96A74E6BE/myApp.app/data.xml, NSUserStringVariant=( Copy ), NSFilePath=/Users/User1/Library/Developer/CoreSimulator/Devices/0E591E5B-2E2F-4CCB-9099-95CE1EA3F557/data/Containers/Bundle/Application/E3C8FAE4-703D-46CA-AC37-A1C96A74E6BE/myApp.app/data.xml, NSDestinationFilePath=/Users/User1/Library/Developer/CoreSimulator/Devices/0E591E5B-2E2F-4CCB-9099-95CE1EA3F557/data/Containers/Data/Application/09F690B3-BDD8-4482-ADDE-E33F30D4B873/Documentsdata.xml, NSUnderlyingError=0x7a67dd80 "The operation couldn’t be completed. File exists"}

Please HELP!


Solution

  • Implement NSFileManagerDelegate and the delegate method

    optional func fileManager(_ fileManager: NSFileManager,
      shouldProceedAfterError error: NSError,
            copyingItemAtURL srcURL: NSURL,
                       toURL dstURL: NSURL) -> Bool
    

    and return true

    Alternatively you could use

    func replaceItemAtURL(_ originalItemURL: NSURL,
                   withItemAtURL newItemURL: NSURL,
              backupItemName backupItemName: String?,
                            options options: NSFileManagerItemReplacementOptions,
              resultingItemURL resultingURL: AutoreleasingUnsafeMutablePointer<NSURL?>) throws