Can't Share Data Between Main App And Extension

Hello,

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.
Answered by darkpaw in 638422022
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).
Accepted Answer
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).
Thank you for the ideas!

I think I've found my issue. My app group var was not spelled correctly.

Thanks Again.
Can't Share Data Between Main App And Extension
 
 
Q