iosswiftwidgetios14

Swift - Widget not able to access app group


I have lately been trying to make a widget and wanted to share a piece of data between my widget and my app.

    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")
    }

The above code works fine on my app, but when I run it on my widget it gives me the following output. I have checked that the app group is correct and is active on both the iOS app and the widget.

[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

Edit:

I have also tried to use UserDefaults, but they don't work either.

The following is the way I use the the FileManager and 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)
}

And the following is how I try to read the data from the widget:

    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
    }()

WidgetExtension app groups: enter image description here

Main app, app groups: enter image description here


Solution

  • I found out what my problem was. I had accidentally selected the release tab under Signing & Capabilities. Which caused my app group to be wrong when checking on release, thus making the error occur. Image of project bar I just had to select All and re-add the app groups capability which made it work again.