Hopefully a simple question, but I'm wondering how I would access UserDefaults data saved in my UIKit app from a SwiftUI Widget? I need to display some of this data in a widget.
Thanks!
Hopefully a simple question, but I'm wondering how I would access UserDefaults data saved in my UIKit app from a SwiftUI Widget? I need to display some of this data in a widget.
Thanks!
You need to use UserDefaults(suiteName:)
instead of UserDefaults.standard
along with an AppGroup. UserDefaults.standard
is only accessible in the app that it is in, it is not available to any of the extensions or other apps that you may make. This is why you have to use an AppGroup.
Once you have created your AppGroup (you can do this in the Signing and Capabilities section) you should have a suiteName
for it, something like:
group.com.my.app.identifier
Then in your UIKit part of your app you can set the values in the AppGroup's UserDefaults in the following way:
if let userDefaults = UserDefaults(suiteName: "group.com.my.app.identifier") {
userDefaults.setValue("value to save", forKey: "Key")
}
And reading them back you can use:
if let userDefaults = UserDefaults(suiteName: "group.com.my.app.identifier") {
let value = userDefaults.string(forKey: "Key")
}
As the Widget will be written in SwiftUI you can use the property wrapper @AppStorage
to access the values:
@AppStorage("Key", store: UserDefaults(suiteName: "group.com.my.app.identifier"))
var value: String = ""
If you have already stored the values that you wish to use in UserDefaults.standard
you will need to copy them across to the UserDefaults(suitName:)
.