我最近一直在尝试制作一个小部件,并想在我的小部件和我的应用程序之间共享一段数据。
static var sharedDataFileURL: URL {
let appGroupIdentifier = "group.com.unknownstudios.yk"
guard let url = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroupIdentifier)
else { preconditionFailure("Expected a valid app group container") }
return url.appendingPathComponent("userID.plist")
}
上面的代码在我的应用程序上运行良好,但是当我在我的小部件上运行它时,它会给出以下输出。我已检查应用程序组是否正确并且在 iOS 应用程序和小部件上均处于活动状态。
[unspecified] container_create_or_lookup_path_for_platform: client is not entitled
[unspecified] container_create_or_lookup_app_group_path_by_app_group_identifier: client is not entitled
Fatal error: Expected a valid app group container: file WidgetExtension/Library.swift, line 143
编辑:
我也尝试过使用 UserDefaults,但它们也不起作用。
以下是我使用FileManager和UserDefaults的方式
UserDefaults(suiteName: "group.com.unknownstudios.yk")!.set("**USERID**", forKey: "userID")
let data = Data("**USERID**".utf8)
do {
try data.write(to: URL.sharedDataFileURL, options: .atomic)
} catch {
print(error.localizedDescription)
}
以下是我尝试从小部件读取数据的方法:
var userID: String? = {
if let userid = UserDefaults(suiteName: "group.com.unknownstudios.yk")!.string(forKey: "userID") {
print(userid)
return userid
} else if let url = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.unknownstudios.yk") {
if let data = try? Data(contentsOf: url.appendingPathComponent("userID.plist")), let string = String(data: data, encoding: .utf8) {
return string
}
}
return nil
}()
您可能还需要仔细检查是否有拼写错误。
$(TeamIdentifierPrefix)
包括尾随的 .
。
我有:
// My bundle includes an entry for $(TeamIdentifierPrefix)
// See https://stackoverflow.com/a/28714850/788168
let teamIdentifierPrefix = Bundle.main.object(forInfoDictionaryKey: "TeamIdentifierPrefix") as! String
location = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.\(teamIdentifierPrefix).com.myteam.myapp")!
.appendingPathComponent("db.sqlite")
.path
它需要是:
// My bundle includes an entry for $(TeamIdentifierPrefix)
// See https://stackoverflow.com/a/28714850/788168
let teamIdentifierPrefix = Bundle.main.object(forInfoDictionaryKey: "TeamIdentifierPrefix") as! String
location = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.\(teamIdentifierPrefix)com.myteam.myapp")!
.appendingPathComponent("db.sqlite")
.path
如:
Wrong: "group.\(teamIdentifierPrefix).com.myteam.myapp"
Right: "group.\(teamIdentifierPrefix)com.myteam.myapp"