Search code examples
iosswiftnsfilemanager

FileManager "File exists" when copying files


I am trying to copy a file (audioFile) to DestinationURl however when I do I get this error:

Unable to create directory Error Domain=NSCocoaErrorDomain Code=516 "“20200116183746+0000.m4a” couldn’t be copied to “Documents” because an item with the same name already exists." UserInfo={NSSourceFilePathErrorKey=/<app>/Documents/20200116183746+0000.m4a, NSUserStringVariant=(
    Copy
), NSDestinationFilePath=<appURL>/Documents/20200116183746+0000.m4a, NSUnderlyingError=0x600003c2d290 {Error Domain=NSPOSIXErrorDomain Code=17 "File exists"}}

Here I my code

            let DirPath = DocumentDirectory.appendingPathComponent(self.txtName.text ?? "NA")
            do
            {
                try FileManager.default.createDirectory(atPath: DirPath!.path, withIntermediateDirectories: true, attributes: nil)
                print("\n\n\nAudio file: \(self.audioFile)\n\n\n")
                let desitationURl = ("\(DirPath!.path)/")
                try FileManager.default.copyItem(atPath: self.audioFile.path, toPath: desitationURl)
            }
            catch let error as NSError
            {
                print("Unable to create directory \(error.debugDescription)")
            }

I have removed the / on let desitationURl = ("(DirPath!.path)/") and I can see that the file has been generated and the folder is generated however nothing is moved.

Any help will be appreciated

Osian


Solution

  • You need to specify the actual name of the destination file, not just the directory it will go inside. The file manager is literally trying to save your file as the directory name. I cleaned your code up a bit to make it more readable, as well:

    guard let dirURL = DocumentDirectory
        .appendingPathComponent(self.txtName.text ?? "NA") else { return }
    
    if !FileManager.default.fileExists(atPath: dirURL.path) {
        do {
            try FileManager.default
                 .createDirectory(atPath: dirURL.path, 
                                  withIntermediateDirectories: true,
                                  attributes: nil)
        } catch let error as NSError {
            print("Unable to create directory \(error.debugDescription)")
        }
    }
    
    print("\n\n\nAudio file: \(audioFile)\n\n\n")
    
    let dstURL = dirURL.appendingPathComponent(audioFile.lastPathComponent)
    do {
        try FileManager.default.copyItem(atPath: audioFile.path, toPath: dstURL.path)
    } catch let error as NSError {
        print("Unable to copy file \(error.debugDescription)")
    }