I have implemented 3 widgets in my app; users can add and remove widgets as suits users. but on some devices, when a user removes the widget from the app and then adds it again the widget doesn't show any data or view until widget gets new data. I have called API and updated data in viewwillappear so that initial data will be shown.
To add a widget:
if let match1 = scoreDtailsViewModel.matchDetails?.match {
UserDefaults.init(suiteName: Constants.widget1KEY)?.setValue(try! PropertyListEncoder().encode(match1) , forKey: "match")
}
if let liveMarket = scoreDtailsViewModel.liveMarket.first {
UserDefaults.init(suiteName: Constants.widget1KEY)?.setValue(try! PropertyListEncoder().encode(liveMarket) , forKey: "liveMarket")
}
if let id = scoreDtailsViewModel.match?.id {
UserDefaults.init(suiteName: Constants.widget1KEY)?.setValue( id, forKey: "match_id")
}
DispatchQueue.main.async(execute: {
NCWidgetController().setHasContent(true, forWidgetWithBundleIdentifier: Constants.widget1BundleIdentifier)
})
To remove the widget:
UserDefaults.init(suiteName: Constants.widget1KEY)?.setValue("" , forKey: "match")
UserDefaults.init(suiteName: Constants.widget1KEY)?.setValue("" , forKey: "liveMarket")
UserDefaults.init(suiteName: Constants.widget1KEY)?.setValue("", forKey: "match_id")
DispatchQueue.main.async(execute: {
NCWidgetController().setHasContent(false, forWidgetWithBundleIdentifier: Constants.widget1BundleIdentifier)
})
How it looks after reading: