import WidgetKit
import SwiftUI
private let widgetGroupdId = "group.home_widget"
extension View {
func widgetBackground(_ backgroundView: some View) -> some View {
if #available(iOSApplicationExtension 17.0, *) {
return containerBackground(for: .widget) {
backgroundView
}
} else {
return background(backgroundView)
}
}
}
struct Provider: TimelineProvider {
func placeholder(in context: Context) -> SimpleEntry {
SimpleEntry(date: Date(), city: "PlaceHolder", temperature: "2°", weatherDescription: "Bulutlu", feelsLikeTemperature: "0°")
}
func getSnapshot(in context: Context, completion: @escaping (SimpleEntry) -> ()) {
let entry: SimpleEntry
if context.isPreview{
entry = placeholder(in: context)
}
else{
let userDefaults = UserDefaults(suiteName: widgetGroupdId)
let city = userDefaults?.string(forKey: "city") ?? "Tirana"
print("City from UserDefaults: (city)")
if let city = userDefaults?.string(forKey: "city") {
print("City from UserDefaults in main app: (city)")
} else {
print("City not found in UserDefaults")
}
entry = SimpleEntry(date: Date(), city: city, temperature: "2°", weatherDescription: "Bulutlu", feelsLikeTemperature: "0°")
}
completion(entry)
}
func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
getSnapshot(in: context) { (entry) in
let timeline = Timeline(entries: [entry], policy: .atEnd)
completion (timeline)
}
}
struct SimpleEntry: TimelineEntry {
let date: Date
let city: String
let temperature: String
let weatherDescription: String
let feelsLikeTemperature: String
}
struct meteo_home_widget_Previews: PreviewProvider {
static var previews: some View {
meteo_home_widgetEntryView(entry: SimpleEntry(date: Date(),city: "Example city", temperature: "2°", weatherDescription: "Buludlu", feelsLikeTemperature: "0°"))
.previewContext(WidgetPreviewContext(family: .systemSmall))
}
}
}
@main
struct meteo_home_widget: Widget {
let kind: String = "meteo_home_widget"
var body: some WidgetConfiguration {
StaticConfiguration(kind: kind, provider: Provider()) { entry in
meteo_home_widgetEntryView(entry: entry)
}
.configurationDisplayName ("My Widget")
.description("This is an example widget.")
.contentMarginsDisabled()
}
}
struct meteo_home_widgetEntryView : View {
var entry: Provider.Entry
var body: some View {
VStack(alignment: .leading) {
HStack {
Image("navigation")
.foregroundColor(Color.white)
Spacer().frame(width: 5)
Text(entry.city).foregroundColor(.white).font(Font.system(size: 18))
}
}
.widgetBackground( Image("cloud")
.resizable()
.aspectRatio(contentMode: .fill )
)
.contentMargins(0)
.padding(0)
}
}
Here in UserDefaults I don’t get city, however in my Flutter app I update this info. I initialize home widget at main dart, and then
HomeWidget.saveWidgetData<String>(
'city',
city,
);
update my city.
In android everything works perfect. I get data. But in iOS there is some problem. I think the problem is with swift code. Thank you in advance for help.