關閉 Mac App 的 Sandbox 模式

彼得潘的 iOS App Neverland
3 min readAug 7, 2020

--

當我們開發 Mac App 時,它預設是 Sandbox 模式,因此若想讀取 App 本身資料夾以外的檔案,需要另外經過使用者的同意。

不過如果 App 沒有要上架 App Store,只想在自己的電腦測試,倒是可以先關閉 Sandbox 模式。

比方彼得潘開發的 Mac App 利用以下程式讀取 Mac 個人帳號下 Documents/book/ 的檔案和資料夾清單,將檔名呈現在表格上。

struct ContentView: View {

@State private var books = [String]()

var body: some View {

List(books, id: \.self) { (book) in
Text(book)
}
.onAppear(perform: {
let documentDirectory = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let path = documentDirectory?.appendingPathComponent("book")
if let filesAndDirectories = try? FileManager.default.contentsOfDirectory(at: path!, includingPropertiesForKeys: nil) {

books = filesAndDirectories.map(\.lastPathComponent)

}
})

}
}

為了方便測試 App,彼得潘先將 Sandbox 關掉。

  • 點選 Project navigator 下的 entitlements 檔。
  • 找到 App Sandbox 欄位。
  • 將它改成 NO。

接著執行 App,App 第一次啟動時會詢問是否同意存取 Document folder 。我們想存取 Document 下的檔案,因此選擇 OK。

Cool,Mac App 畫面的表格列出了彼得潘在 /Documents/book/ 下收藏的電子書檔名。

--

--

彼得潘的 iOS App Neverland
彼得潘的 iOS App Neverland

Written by 彼得潘的 iOS App Neverland

彼得潘的 Swift iOS App 程式設計入門,文組生的 Swift iOS App 程式設計入門,彼得潘的 Flutter 跨平台 App 程式設計入門講師,彼得潘的 Swift 程式設計入門,App程式設計入門作者,http://apppeterpan.strikingly.com

No responses yet