Background: I’ve applied a widget in a SwiftUI challenge. The primary app permits individuals to see bus service schedules in any respect bus stops. They will ‘favorite’ buses at stops they use regularly. These favourites are saved domestically utilizing SwiftData. The widget permits customers to view the schedule of the highest 4 favorite buses within the widget.
I’ve applied it such that each time there’s a context.insert or context.delete in the principle app, I subsequently name WidgetCenter.shared.reloadAllTimelines() in order that the widgets content material is up to date with the newest favourites.
I’ve used an asynchronous Job throughout the physique of the widget Timeline supplier to get the entry and replace the timeline.
Code inside timeline supplier:
@MainActor
func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
Job{
//1.Get from Core Information
let faveServicesSaved = getFavourites()
print("Widget: Get Favourites Triggered (faveServicesSaved.rely)")
//Get arrival information
let faveServicesReturned = strive? await fetchAllData(companies: faveServicesSaved)
print("Widget: Arrival Information Retrieved (faveServicesReturned?.rely)")
//Type by location
let faveServicesSorted = sortByLocation(faveServicesReturned ?? [])
print("Widget: Sorted by location (faveServicesSorted.rely)")
let nearestFaveServices = faveServicesSorted.prefix(4)
print("Widget: Nearest fave companies (nearestFaveServices.rely)")
//select the primary 4 for show
let entry = Favourites(date: Date(), companies: Array(nearestFaveServices))
let timeline = Timeline(entries: [entry], coverage: .by no means)
completion(timeline)
}
}
//Since can't entry @Question from inside Timeline supplier, have to get information utilizing Core Information
@MainActor
personal func getFavourites() ->[FaveService]{
guard let container = strive? ModelContainer(for: FaveService.self) else {
print("Widget: Downside with container setup")
return []
}
let descriptor = FetchDescriptor<FaveService>()
let faves = strive? container.mainContext.fetch(descriptor)
print("Widget (faves?.rely)")
return faves ?? []
}
Downside: I discover that the replace to widget content material is lagging by one replace i.e. the primary time I add a favorite from the principle app it does not seem within the content material. Once I add the second favorite, the primary one seems. Once I add a 3rd favorite, the second seems. and so forth.
What I’ve tried:
- As I discussed, throughout the physique of the principle app I’ve double checked to make sure that reloadAllTimelines is being referred to as after a context.insert.
- I’ve checked to make sure that all code is working on the principle thread so there are not any updating conflicts.
- I’ve checked that the mannequin container is accurately setup for the primary pull
- I’ve tried different replace insurance policies together with .atEnd and .after(now.advance(by: 60)).
Any concepts what could be inflicting this lagged replace?