group - userdefaults swift 3




Sharing UserDefaults between extensions (2)

Creating a Today widget and I am using UserDefaults(suiteName:) to persist some data. In the main application I am using UserDefaults.standard(). This can't be read (or can it?) by the extension which is why I use the suiteName: constructor.

Data that user persist to UserDefaults.standard() in the main app needs to be available in the extension.

At this time I am persisting to both so that the values can be shared

 UserDefaults.standard().set:...forKey:...
 UserDefaults(suiteName:...)().set:...forKey:...
 ...

Question is should I drop UserDefaults.standard() all together and just use UserDefaults(suiteName:) in my application, or is this bad practice and if so why?

Edit: I am using an App group container. For clarification I am asking should I just replace standard() with suiteName: throughout my project?


A simple example:

if let userDefaults = UserDefaults(suiteName: "group.your.bandle.here") {
    userDefaults.set("test 1" as AnyObject, forKey: "key1")
    userDefaults.set("test 2" as AnyObject, forKey: "key2")
    userDefaults.synchronize()
}

and you can read it later:

if let userDefaults = UserDefaults(suiteName: "group.your.bandle.here") {
    let value1 = userDefaults.string(forKey: "key1")
    let value2 = userDefaults.string(forKey: "key2")
    ...
}

Make sure App Groups is enabled for ALL of your targets (your app and extensions targets) in Capabilities tab

And then use the group's identifier above as suite name when create UserDefaults:

let userDefaults = UserDefaults(suiteName: "group.com.YourCompany.YourApp")






ios10-today-widget