2016-12-17 157 views
2

我正在創建一個macOS應用程序,該應用程序在其Bundle目錄中附帶一些.zip文件。使用NSSavePanel將文件從Bundle保存到桌面

用戶應該能夠將這些文件從我的應用程序保存到自定義目錄。

我發現NSSavePanel,認爲這是正確的做法 - 這是我到目前爲止有:

@IBAction func buttonSaveFiles(_ sender: Any) { 

    let savePanel = NSSavePanel() 

    let bundleFile = Bundle.main.resourcePath!.appending("/MyCustom.zip") 

    let targetPath = NSHomeDirectory() 
    savePanel.directoryURL = URL(fileURLWithPath: targetPath.appending("/Desktop")) 
    // Is appeding 'Desktop' a good solution in terms of localisation? 

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

    savePanel.beginSheetModal(for: self.view.window!, completionHandler: {_ in }) 

} 

我無法找出如何「交出」的bundleFilesavePanel

所以我的主要問題是:如何將應用程序包中的文件保存/複製到自定義目錄?

其他問題取決於NSSavePanel:1)它似乎沒有默認本地化(我的Xcode方案設置爲德語,但面板以英文顯示),我必須自己定製嗎? 2)有沒有方法可以展示默認擴展的面板?

+0

運行搜索包或NSBundle將有所幫助。 –

+0

@ElTomato我已經使用'Bundle'來查找bundleFile的路徑(參見上面的代碼)。這對我描述的問題沒有幫助。 – ixany

+0

哦,對不起...讓我想想,我會回來的。 –

回答

3

您應該使用Bundle.main.url來獲取您現有的文件URL,然後使用面板獲取目標URL,然後複製該文件。該面板對文件不做任何處理,只是獲取他們的URL。

例子:

// the panel is automatically displayed in the user's language if your project is localized 
let savePanel = NSSavePanel() 

let bundleFile = Bundle.main.url(forResource: "MyCustom", withExtension: "zip")! 

// 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 = true 

if let url = savePanel.url, savePanel.runModal() == NSFileHandlingPanelOKButton { 
    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") 
} 

而且,請注意,面板正在擴大與否是用戶的選擇,你不能從你的應用程序迫使它。

+0

非常感謝!很好的解決方案,工作正常你也不知道爲什麼'NSSavePanel'沒有被翻譯/本地化嗎?我認爲所有系統提供的UI元素都應該自動以相關語言顯示。 – ixany

+1

不客氣。如果* [您的項目已經本地化],該面板將自動以用戶的語言顯示*(http://take.ms/x5P8a)。從列表中添加新語言已足夠,如果不想實際實現本地化,則不必實現本地化 - 但您必須至少在此列表中添加語言,因爲該面板將需要它們。 – Moritz

+1

[適用於Xcode截圖的正確鏈接](https://monosnap.com/file/P6rGrVhQsGaquhVdlzMNDK0FUVXFq6.png)用於添加本地化。 – Moritz

相關問題