How to overwrite a file with NSFileManager when copying?

后端 未结 9 720
广开言路
广开言路 2020-12-02 14:13

I\'m using this method to copy a file:

[fileManager copyItemAtPath:sourcePath toPath:targetPath error:&error];

I want to overwrite a fi

9条回答
  •  甜味超标
    2020-12-02 14:43

    Detect file exists error, delete the destination file and copy again.

    Sample code in Swift 2.0:

    class MainWindowController: NSFileManagerDelegate {
    
        let fileManager = NSFileManager()
    
        override func windowDidLoad() {
            super.windowDidLoad()
            fileManager.delegate = self
            do {
                try fileManager.copyItemAtPath(srcPath, toPath: dstPath)
            } catch {
                print("File already exists at \'\(srcPath)\':\n\((error as NSError).description)")
            }
        }
    
        func fileManager(fileManager: NSFileManager, shouldProceedAfterError error: NSError, copyingItemAtPath srcPath: String, toPath dstPath: String) -> Bool {
            if error.code == NSFileWriteFileExistsError {
                do {
                    try fileManager.removeItemAtPath(dstPath)
                    print("Existing file deleted.")
                } catch {
                    print("Failed to delete existing file:\n\((error as NSError).description)")
                }
                do {
                    try fileManager.copyItemAtPath(srcPath, toPath: dstPath)
                    print("File saved.")
                } catch {
                    print("File not saved:\n\((error as NSError).description)")
                }
                return true
            } else {
                return false
            }
        }
    }
    

提交回复
热议问题