-
Notifications
You must be signed in to change notification settings - Fork 3
/
DataManager.swift
67 lines (55 loc) · 1.98 KB
/
DataManager.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
//
// DataManager.swift
// SmogWatch WatchKit Extension
//
// Created by Kuba Suder on 15.06.2020.
// Copyright © 2020 Kuba Suder. Licensed under WTFPL license.
//
import ClockKit
import Foundation
import os.log
private let minimumIntervalBetweenUpdates: TimeInterval = 5 * 60
private let log = OSLog(subsystem: OSLog.subsystem, category: "Data Manager")
class DataManager {
let loader = KrakowPiosDataLoader()
let dataStore = DataStore()
var canUpdateDataNow: Bool {
if let lastUpdate = dataStore.lastUpdateDate {
return Date().timeIntervalSince(lastUpdate) > minimumIntervalBetweenUpdates
} else {
return true
}
}
func updateDataIfNeeded() {
if canUpdateDataNow {
updateData()
} else {
os_log("Not loading data since it was last updated at %@", log: log, dataStore.lastUpdateDate! as NSDate)
}
}
func updateData(callback: ((Bool) -> ())? = nil) {
loader.fetchData { success in
NotificationCenter.default.post(name: DataStore.dataLoadedNotification, object: nil)
if success {
self.reloadComplications()
}
if self.dataStore.hasEnoughPoints {
callback?(success)
} else {
let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: Date())
self.loader.fetchData(date: yesterday) { success in
NotificationCenter.default.post(name: DataStore.dataLoadedNotification, object: nil)
callback?(success)
}
}
}
}
func reloadComplications() {
let server = CLKComplicationServer.sharedInstance()
os_log("Requesting reload of complications", log: log)
for complication in server.activeComplications ?? [] {
os_log("- %{public}@", log: log, complication.family.description)
server.reloadTimeline(for: complication)
}
}
}