Commit e984a98e by Demid Merzlyakov

IOS-101: widget: load up to date data.

parent a5fe1230
......@@ -17,16 +17,6 @@ import CoreDataStorage
class WeatherProvider: TimelineProvider {
typealias Entry = WeatherEntry
private lazy var manager: LocationManager = {
LocationManager.shared = LocationManager(weatherUpdateSource: WdtWeatherSource(),
healthSource: BlendHealthSource(),
nwsAlertsManager: NWSAlertsManager(),
fipsSource: BlendFIPSSource(),
pushNotificationsManager: nil,
storage: DelayedSaveStorage(storage: CoreDataStorage(), delay: 2))
return LocationManager.shared
}()
func placeholder(in context: Context) -> WeatherEntry {
return WeatherEntry()
}
......@@ -35,13 +25,45 @@ class WeatherProvider: TimelineProvider {
let entry = WeatherEntry()
completion(entry)
}
var storage: Storage = CoreDataStorage()
var weatherSource: WeatherSource = WdtWeatherSource()
func getTimeline(in context: Context, completion: @escaping (Timeline<WeatherEntry>) -> Void) {
guard let currentLocation = manager.selectedLocation else { return }
manager.updateWeather(for: currentLocation, updateType: .preferIncremental) { updatedLocation in
guard let location = updatedLocation else { return }
func isFreshEnough(_ location: Location) -> Bool {
guard let lastTimeUpdated = location.lastWeatherUpdateDate else {
return false
}
return Date().timeIntervalSince(lastTimeUpdated) < self.weatherSource.weatherUpdateInterval
}
func getUpToDateLocation(_ completion: @escaping (Location?) -> () ) {
storage.load { [weak self] (locations, selectedIndex, error) in
guard let self = self else {
completion(nil)
return
}
guard let locations = locations, let selectedIndex = selectedIndex, selectedIndex < locations.count else {
completion(nil)
return
}
let selectedLocation = locations[selectedIndex]
guard !self.isFreshEnough(selectedLocation) else {
completion(selectedLocation)
return
}
self.weatherSource.updateWeather(for: selectedLocation, type: .preferIncremental) { updatedLocation, error in
guard let updatedLocation = updatedLocation else {
completion(selectedLocation)
return
}
completion(updatedLocation)
}
}
}
func getTimeline(in context: Context, completion: @escaping (Timeline<WeatherEntry>) -> Void) {
getUpToDateLocation { location in
let nextRefresh = Calendar.current.date(byAdding: .minute, value: 30, to: Date())!
let entry = WeatherEntry(location: location, date: nextRefresh)
let timeline = Timeline(entries: [entry], policy: .atEnd)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment