问题
I want to share one variable from my UIKit File to my Widget Extension created with SwiftUI. I followed this here. Please look at the answer from J Arango.
But i dont understand the last part there.
I have to use import MySharedObjects
.
So I did this:
import MySharedObject
struct testing {
let mySharedObject = MySharedObject(name: "My Name", lastName: "My Last Name")
do {
let data = try JSONEncoder().encode(mySharedObject)
/// Make sure to use your "App Group" container suite name when saving and retrieving the object from UserDefaults
let container = UserDefaults(suiteName:"group.com.widgetTest.widgetContainer")
container?.setValue(data, forKey: "sharedObject")
/// Used to let the widget extension to reload the timeline
WidgetCenter.shared.reloadAllTimelines()
} catch {
print("Unable to encode WidgetDay: \(error.localizedDescription)")
}
}
But I get the following errors.
- Extra argument at position #1, #2 in call
- Missing argument for parameter from call
- insert from : <#Decoder#>
- expected declaration where I use the
do
part.
回答1:
- Save data to
UserDefaults
in your main App:
UserDefaults(suiteName: <your_app_group>)!.set("test", forKey: "test")
- Read data from
UserDefaults
in your Widget:
let testStr = UserDefaults(suiteName: <your_app_group>)!.string(forKey: "test")
If you want to save other types see:
- How can I use UserDefaults in Swift?
来源:https://stackoverflow.com/questions/63995776/sharing-data-with-appgroup