Hello,
I've recently added a widget extension to my app. But I've been having trouble sharing data between the two using UserDefaults.
App groups are turned on in both targets, but the data is not shared.
Any ideas as to why this is happening would be appreciated.
Thank you.
I've recently added a widget extension to my app. But I've been having trouble sharing data between the two using UserDefaults.
Code
Shared Code
Code Block swift var AppGroup: String { "group.someGroup" }
Main App
Code Block swift UserDefaults(suiteName: AppGroup)!.setValue(data, forKey: "TimeLine") // sets the value for main app.
Widget Extension
Code Block swift let data = UserDefaults(suiteName: AppGroup)!.data(forKey: "TimeLine") // can't get the value in extension.
App groups are turned on in both targets, but the data is not shared.
Any ideas as to why this is happening would be appreciated.
Thank you.
Have you tried synchronising the defaults after changing them in the main app, to ensure they're saved?
If that doesn't fix it, can you NSLog() the UserDefaults(suiteName: AppGroup) to see if the data is in there?
Can you write and read different data types other than "data"? Maybe save an Int in there?
Also, as an aside, the AppGroup doesn't change so you can use a let: let kAppGroup: String = "group.someGroup" (I use "kBlahBlahBlah" to denote a constant).
If that doesn't fix it, can you NSLog() the UserDefaults(suiteName: AppGroup) to see if the data is in there?
Can you write and read different data types other than "data"? Maybe save an Int in there?
Also, as an aside, the AppGroup doesn't change so you can use a let: let kAppGroup: String = "group.someGroup" (I use "kBlahBlahBlah" to denote a constant).