MacSergey
MacSergey

Reputation: 15

Swift Data to today widget from host application

How can I transfer data from the host application into a widget? I use the same function from framework in the application and widget. Application receives data, and the widget returns an empty array.

public func readLED() -> [LEDController] {
    let defaults = UserDefaults.standard()
    if let saved = defaults.object(forKey: "ledControllers") as? NSData {
        return (NSKeyedUnarchiver.unarchiveObject(with: saved as Data) as! [LEDController])
    }
    return []
}

Upvotes: 0

Views: 1591

Answers (2)

TimeLoRd
TimeLoRd

Reputation: 31

Apologize for my level of English.

To share data between AppHost and the Widget, you should save your userDefault data like this:

Example in a static class

class UserDefaultDataHelper: NSObject {
    static func saveKeyToGroupApp(_ value: AnyObject?, withKey key:String) -> Void {
        UserDefaults(suiteName: "group.com.test")!.set(value, forKey: key)
        UserDefaults(suiteName: "group.com.test")!.synchronize()
    }

    //and to read values 

    static func loadKeyToGroupApp(_ key:String)  -> AnyObject? {
        if let loadedValue = UserDefaults(suiteName: "group.com.test")?.object(forKey: key){
            return loadedValue as AnyObject?
        }
        return nil
    }
}

and read the data in the Widget like this:

let ledcontrollerdata = UserDefaultDataHelper.loadKeyToGroupApp("ledControllers")

UserDefaultDataHelper.saveKey(yourData as AnyObject?, withKey: "ledControllers")

You can share data between several apps, widget, etc, BUT only if these are in a "App Groups" with a Bundle ID group. You should use this Bundle ID group in group.com.test and both projects should have their respective entitlements and both configure targets in Capabilities -> AppGroups, select your AppGroupDomain.

Upvotes: 1

dispatchswift
dispatchswift

Reputation: 1056

You won't be able to use UserDefaults.standard() to share data between your containing app and extension.

From Apple:

Even though an app extension bundle is nested within its containing app’s bundle, the running app extension and containing app have no direct access to each other’s containers.

So....

To enable data sharing, use Xcode or the Developer portal to enable app groups for the containing app and its contained app extensions.

Upvotes: 0

Related Questions