【问题标题】:Copy and Save File from Application Bundle to Desktop / somewhere else将文件从应用程序包复制并保存到桌面/其他地方
【发布时间】:2020-04-23 16:00:00
【问题描述】:

我想将 MIDI 文件保存到某个文件夹。但不幸的是,只是得到一个“无标题”的 txt 文件。

我找到了我尝试过的这段代码:

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

我可以改进什么以将 MIDI 文件从应用程序包复制到例如桌面??

谢谢!

【问题讨论】:

    标签: swift macos cocoa nsbundle


    【解决方案1】:

    查看我为将文件从应用程序包复制到某人 Mac 上的某个位置而编写的一些旧代码,我不得不将文件名作为附加路径组件附加到目标 URL 以使文件正确复制.使用您的代码示例,代码将类似于以下内容:

    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.
    

    【讨论】:

    • 感谢您的快速响应,但我仍在解决问题。 open on /Users/lulutuschk/Desktop/Untitled/Melody.mid: Not a directory “Melody.mid” couldn’t be copied to “Untitled”. /Untitled/ 来自哪里 - 我怎样才能避免它? @MarkSzymczyk
    • 我想我明白了 - 我刚刚找到了这段代码 url.deletingLastPathComponent() --> 它删除了 Untitled 并且一切正常 - 非常感谢 @MarkSzymczyk
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-27
    • 1970-01-01
    • 2020-08-03
    相关资源
    最近更新 更多