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?
You cannot use shared
UserDefaults
to share data between and App Extension
and itsHost App
. You have to useApp Group
, i.e. a shared containerUserDefaults(suiteName:)
to share data.For more, refer to: https://developer.apple.com/library/content/documentation/General/Conceptual/ExtensibilityPG/ExtensionScenarios.html#//apple_ref/doc/uid/TP40014214-CH21-SW1
How to use App Groups: https://github.com/pgpt10/Today-Widget
Standard or SuitName?
Use standard one for data that is only for Host App. Use suiteName for data that you want to share between Extension and Host App. Just don't persist the same data in both of them. Avoid data redundancy. Use both of them according to the context.
A simple example:
and you can read it later: