macOS Sandboxed app 多个程序共享 存入 Group preference的bookmark失败

Apple 论坛的文章:Share security scoped bookmark in app group?

原文:


Working on the same thing, I also ran into this. Did you manage to solve it?
I think I got this working using the following recipe:

0) setup "group app" and appropriate entitlements, think of:
com.apple.security.application-groups
com.apple.security.files.bookmarks.app-scope
com.apple.security.files.user-selected.read-write

1) In the UI-app, use the NSOpenPanel to obtain a directory-url.
2) Use url.bookmarkData with the option .minimalBookmark and save this data to the user defaults of the group 
(using UserDefaults(suiteName: "groupname") for example). This will store a regular bookmark in the userdefaults of the group-container.
3) Do NOT close the UI-app yet, but first run the command-line app, read the data from the group-defaults and 
using the data resolve the url BookmarkData using the option .withoutUI
4) Then, in order to persist the use of the url in the Helper command-line app, create a security scoped url using 
url.bookmarkData with the option .withSecurityScope
5) Write the data to the local user defaults of the command-line app, and next time, read the data from the user 
defaults of the command-line app and resolve the url from data with the option .withSecurityScope
6) use: let succeeded: Bool = permissionURL.startAccessingSecurityScopedResource()

The boolean will be true.

So, note an important thing: you can NOT create a security scoped bookmark in the main app, write it to the group, 
read that from a helper command-line utility and resolve it. You will get: "error: The file couldn’t be opened because 
it isn’t in the correct format."
But a normal Bookmark works while both programs are running, which gives you a chance to read the normal 
Bookmark from the group-defaults and write the security scoped Bookmark to the userdefaults of the Helper-app 
(which needs to be written by the Helper-app, NOT by the main UI-app).

意思就是主工程 MainApp 存入的安全书签不能被子工程SubApp解析访问

解决方法,将MainApp 存入的 bookmark 转存一下:
1)MainApp 通过 NSOpenPanel 得到的URL 必须以 .minimalBookmark Option 存入bookmark.
2)不要关闭MainApp,保证 MainApp 和 SubApp 在同时运行,SubApp 以 .withoutUI 解析上面存入的bookmark
3)SubApp 再以 .withSecurityScope 将步骤2中解析的url 存为bookmark
4)SubApp 此时可以长期解析访问3中存入的bookmark了:
let succeeded: Bool = permissionURL.startAccessingSecurityScopedResource()

你可能感兴趣的:(macOS开发,Xcode,macos)