forked from cyoung1024/Loop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExtensionDelegate.swift
258 lines (212 loc) · 9.74 KB
/
ExtensionDelegate.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
//
// ExtensionDelegate.swift
// WatchApp Extension
//
// Created by Nathan Racklyeft on 8/29/15.
// Copyright © 2015 Nathan Racklyeft. All rights reserved.
//
import WatchConnectivity
import WatchKit
import HealthKit
import Intents
import os
import os.log
import UserNotifications
final class ExtensionDelegate: NSObject, WKExtensionDelegate {
private(set) lazy var loopManager = LoopDataManager()
private let log = OSLog(category: "ExtensionDelegate")
private var observers: [NSKeyValueObservation] = []
private var notifications: [NSObjectProtocol] = []
static func shared() -> ExtensionDelegate {
return WKExtension.shared().extensionDelegate
}
override init() {
super.init()
let session = WCSession.default
session.delegate = self
// It seems, according to [this sample code](https://developer.apple.com/library/prerelease/content/samplecode/QuickSwitch/Listings/QuickSwitch_WatchKit_Extension_ExtensionDelegate_swift.html#//apple_ref/doc/uid/TP40016647-QuickSwitch_WatchKit_Extension_ExtensionDelegate_swift-DontLinkElementID_8)
// that WCSession activation and delegation and WKWatchConnectivityRefreshBackgroundTask don't have any determinism,
// and that KVO is the "recommended" way to deal with it.
observers.append(session.observe(\WCSession.activationState) { [weak self] (session, change) in
self?.log.default("WCSession.applicationState did change to %d", session.activationState.rawValue)
DispatchQueue.main.async {
self?.completePendingConnectivityTasksIfNeeded()
}
})
observers.append(session.observe(\WCSession.hasContentPending) { [weak self] (session, change) in
self?.log.default("WCSession.hasContentPending did change to %d", session.hasContentPending)
DispatchQueue.main.async {
self?.loopManager.sendDidUpdateContextNotificationIfNecessary()
self?.completePendingConnectivityTasksIfNeeded()
}
})
notifications.append(NotificationCenter.default.addObserver(forName: LoopDataManager.didUpdateContextNotification, object: loopManager, queue: nil) { [weak self] (_) in
DispatchQueue.main.async {
self?.loopManagerDidUpdateContext()
}
})
session.activate()
}
deinit {
for notification in notifications {
NotificationCenter.default.removeObserver(notification)
}
}
func applicationDidFinishLaunching() {
UNUserNotificationCenter.current().delegate = self
if #available(watchOSApplicationExtension 5.0, *) {
INRelevantShortcutStore.default.registerShortcuts()
}
}
func applicationDidBecomeActive() {
if WCSession.default.activationState != .activated {
WCSession.default.activate()
}
}
func applicationWillResignActive() {
UserDefaults.standard.startOnChartPage = (WKExtension.shared().visibleInterfaceController as? ChartHUDController) != nil
}
// Presumably the main thread?
func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) {
loopManager.requestGlucoseBackfillIfNecessary()
for task in backgroundTasks {
switch task {
case is WKApplicationRefreshBackgroundTask:
log.default("Processing WKApplicationRefreshBackgroundTask")
break
case let task as WKSnapshotRefreshBackgroundTask:
log.default("Processing WKSnapshotRefreshBackgroundTask")
task.setTaskCompleted(restoredDefaultState: false, estimatedSnapshotExpiration: Date(timeIntervalSinceNow: TimeInterval(minutes: 5)), userInfo: nil)
return // Don't call the standard setTaskCompleted handler
case is WKURLSessionRefreshBackgroundTask:
break
case let task as WKWatchConnectivityRefreshBackgroundTask:
log.default("Processing WKWatchConnectivityRefreshBackgroundTask")
pendingConnectivityTasks.append(task)
if WCSession.default.activationState != .activated {
WCSession.default.activate()
}
completePendingConnectivityTasksIfNeeded()
return // Defer calls to the setTaskCompleted handler
default:
break
}
if #available(watchOSApplicationExtension 4.0, *) {
task.setTaskCompletedWithSnapshot(false)
} else {
task.setTaskCompleted()
}
}
}
private var pendingConnectivityTasks: [WKWatchConnectivityRefreshBackgroundTask] = []
private func completePendingConnectivityTasksIfNeeded() {
if WCSession.default.activationState == .activated && !WCSession.default.hasContentPending {
pendingConnectivityTasks.forEach { (task) in
self.log.default("Completing WKWatchConnectivityRefreshBackgroundTask %{public}@", String(describing: task))
if #available(watchOSApplicationExtension 4.0, *) {
task.setTaskCompletedWithSnapshot(false)
} else {
task.setTaskCompleted()
}
}
pendingConnectivityTasks.removeAll()
}
}
func handle(_ userActivity: NSUserActivity) {
if #available(watchOSApplicationExtension 5.0, *) {
switch userActivity.activityType {
case NSUserActivity.newCarbEntryActivityType, NSUserActivity.didAddCarbEntryOnWatchActivityType:
if let statusController = WKExtension.shared().visibleInterfaceController as? HUDInterfaceController {
statusController.addCarbs()
}
default:
break
}
}
}
private func updateContext(_ data: [String: Any]) {
guard let context = WatchContext(rawValue: data) else {
log.error("Could not decode WatchContext: %{public}@", data)
return
}
if context.preferredGlucoseUnit == nil {
let type = HKQuantityType.quantityType(forIdentifier: .bloodGlucose)!
loopManager.healthStore.preferredUnits(for: [type]) { (units, error) in
context.preferredGlucoseUnit = units[type]
DispatchQueue.main.async {
self.loopManager.updateContext(context)
}
}
} else {
DispatchQueue.main.async {
self.loopManager.updateContext(context)
}
}
}
private func loopManagerDidUpdateContext() {
dispatchPrecondition(condition: .onQueue(.main))
if WKExtension.shared().applicationState != .active {
WKExtension.shared().scheduleSnapshotRefresh(withPreferredDate: Date(), userInfo: nil) { (error) in
if let error = error {
self.log.error("scheduleSnapshotRefresh error: %{public}@", String(describing: error))
}
}
}
// Update complication data if needed
let server = CLKComplicationServer.sharedInstance()
for complication in server.activeComplications ?? [] {
log.default("Reloading complication timeline")
server.reloadTimeline(for: complication)
}
}
}
extension ExtensionDelegate: WCSessionDelegate {
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
if activationState == .activated {
updateContext(session.receivedApplicationContext)
}
}
func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String : Any]) {
log.default("didReceiveApplicationContext")
updateContext(applicationContext)
}
// This method is called on a background thread of your app
func session(_ session: WCSession, didReceiveUserInfo userInfo: [String : Any] = [:]) {
let name = userInfo["name"] as? String ?? "WatchContext"
log.default("didReceiveUserInfo: %{public}@", name)
switch name {
case LoopSettingsUserInfo.name:
if let settings = LoopSettingsUserInfo(rawValue: userInfo)?.settings {
DispatchQueue.main.async {
self.loopManager.settings = settings
}
} else {
log.error("Could not decode LoopSettingsUserInfo: %{public}@", userInfo)
}
case "WatchContext":
// WatchContext is the only userInfo type without a "name" key. This isn't a great heuristic.
updateContext(userInfo)
default:
break
}
}
}
extension ExtensionDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.badge, .sound, .alert])
}
}
extension ExtensionDelegate {
/// Global shortcut to present an alert for a specific error out-of-context with a specific interface controller.
///
/// - parameter error: The error whose contents to display
func present(_ error: Error) {
dispatchPrecondition(condition: .onQueue(.main))
WKExtension.shared().rootInterfaceController?.presentAlert(withTitle: error.localizedDescription, message: (error as NSError).localizedRecoverySuggestion ?? (error as NSError).localizedFailureReason, preferredStyle: .alert, actions: [WKAlertAction.dismissAction()])
}
}
fileprivate extension WKExtension {
var extensionDelegate: ExtensionDelegate! {
return delegate as? ExtensionDelegate
}
}