我想将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文件从应用程序捆绑包复制到例如桌面电脑?
谢谢!
[查看我写的一些旧代码,将文件从应用程序包复制到某人的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.