Copy and Save File from Application Bundle to Desktop / somewhere else

174 Views Asked by At

I want to save a MIDI-file to a certain folder. But unfortunately just get an "Untitled" txt file.

I found this code which I tried:

        let savePanel = NSSavePanel()

        let bundleFile = Bundle.main.url(forResource: "Melody", withExtension: "mid")!

        // this is a preferred method to get the desktop URL
        savePanel.directoryURL = FileManager.default.urls(for: .desktopDirectory, in: .userDomainMask).first!

        savePanel.message = "My custom message."
        savePanel.nameFieldStringValue = "MyFile"
        savePanel.showsHiddenFiles = false
        savePanel.showsTagField = false
        savePanel.canCreateDirectories = true
        savePanel.allowsOtherFileTypes = false
        savePanel.isExtensionHidden = false

        if let url = savePanel.url, savePanel.runModal() == NSApplication.ModalResponse.OK {
            print("Now copying", bundleFile.path, "to", url.path)
            // Do the actual copy:
            do {
             try FileManager().copyItem(at: bundleFile, to: url)
            } catch {
             print(error.localizedDescription)

        } else {
            print("canceled")
        }

What can I improve to copy the MIDI-File from the Application Bundle to the e.g. Desktop??

Thanks!

1

There are 1 best solutions below

2
Swift Dev Journal On

Looking over some old code I wrote to copy a file from the app bundle to a location on someone's Mac, I had to append the name of the file as an additional path component to the destination URL to get the file to copy properly. Using your code example, the code would look similar to the following:

let name = "Melody.mid"
// url is the URL the user chose from the Save panel.
destinationURL = url.appendingPathComponent(name)
// Use destinationURL instead of url as the to: argument in FileManager.copyItem.