WatchConnectivityService.swift
7.65 KB
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
import Foundation
import UIKit
import WatchConnectivity
/// iPhone-side WatchConnectivity wrapper.
/// This keeps Flutter-facing WearEngine APIs mapped to Apple Watch behavior.
final class WatchConnectivityService: NSObject {
static let shared = WatchConnectivityService()
private(set) var isPaired = false
private(set) var isReachable = false
private(set) var isWatchAppInstalled = false
private override init() {
super.init()
}
@discardableResult
func activate() -> Bool {
guard WCSession.isSupported() else { return false }
let session = WCSession.default
session.delegate = self
if session.activationState == .notActivated {
session.activate()
}
refreshState()
return true
}
func refreshState() {
guard WCSession.isSupported() else {
isPaired = false
isReachable = false
isWatchAppInstalled = false
return
}
let session = WCSession.default
isPaired = session.isPaired
isReachable = session.isReachable
isWatchAppInstalled = session.isWatchAppInstalled
}
func hasAvailableDevices() -> Bool {
activate()
refreshState()
return isPaired && isWatchAppInstalled
}
func currentDeviceInfo() -> WearDeviceInfo? {
activate()
refreshState()
guard isPaired else { return nil }
return WearDeviceInfo(
deviceId: nil,
deviceName: "Apple Watch",
isPaired: isPaired,
isReachable: isReachable,
isWatchAppInstalled: isWatchAppInstalled
)
}
func transferLoginInfo(userInfo: UserInfoModel?){
guard activate() else { return }
let params = loginPayload(userInfo: userInfo)
do{
try WCSession.default.updateApplicationContext(params)
print("Send Watch updateApplicationContext: \(params)")
}catch{
print("Error Send Watch updateApplicationContext: \(params)")
}
}
func sendLoginInfoMessage(userInfo: UserInfoModel?) -> Bool {
guard let userInfo else {
return sendCommandMessage(AppGroupMessageKey.logout)
}
guard let json = userInfo.jsonString else {
return false
}
return sendCommandMessage(AppGroupMessageKey.login, json: json)
}
private func loginPayload(userInfo: UserInfoModel?) -> [String: Any] {
guard var params = userInfo?.toJson(), !params.isEmpty else {
return ["command": AppGroupMessageKey.logout]
}
params["command"] = AppGroupMessageKey.login
return params
}
func sendTextMessage(_ message: String) -> Bool {
activate()
guard WCSession.default.isReachable else { return false }
WCSession.default.sendMessage(["message": message], replyHandler: nil) { error in
print("Watch message failed: \(error.localizedDescription)")
}
return true
}
func sendCommandMessage(_ message: String, json: String? = nil) -> Bool {
activate()
guard WCSession.default.isReachable else { return false }
var params: [String: Any] = [
"command": message
]
params["json"] = json
WCSession.default.sendMessage(params, replyHandler: nil) { error in
print("Watch message send failed: \(error.localizedDescription)")
}
return true
}
func sendWatchThemeChangedMessage(
theme: WatchTransformTheme,
completion: @escaping (Result<Bool, Error>) -> Void
) {
var payload: [String: Any] = [
"theme_id": Int(theme.themeId),
"theme_name": theme.themeName,
"energetic_description": theme.energeticDescription,
"normal_description": theme.normalDescription,
"slight_stressful_description": theme.slightStressfulDescription,
"stressful_description": theme.stressfulDescription,
]
payload["energetic_image"] = theme.energeticImage?.data
payload["normal_image"] = theme.normalImage?.data
payload["slight_stressful_image"] = theme.slightStressfulImage?.data
payload["stressful_image"] = theme.stressfulImage?.data
sendReliableCommandMessage(
AppGroupMessageKey.reloadTheme,
payload: payload,
completion: completion
)
}
func deleteWatchTheme(_ completion: @escaping (Result<Bool, Error>) -> Void) {
sendReliableCommandMessage(
AppGroupMessageKey.deleteTheme,
completion: completion
)
}
private func commandPayload(
_ message: String,
json: String? = nil,
payload: [String: Any]? = nil
) -> [String: Any] {
var params: [String: Any] = [
"command": message
]
params["json"] = json
if let payload {
params["payload"] = payload
}
return params
}
private func sendReliableCommandMessage(
_ message: String,
json: String? = nil,
payload: [String: Any]? = nil,
completion: @escaping (Result<Bool, Error>) -> Void
) {
guard activate() else {
completion(.success(false))
return
}
let params = commandPayload(message, json: json, payload: payload)
WCSession.default.transferUserInfo(params)
if WCSession.default.isReachable {
WCSession.default.sendMessage(params, replyHandler: { _ in
completion(.success(true))
}) { error in
print("Watch reliable message send failed: \(error.localizedDescription)")
completion(.success(true))
}
} else {
completion(.success(true))
}
}
}
extension WatchConnectivityService: WCSessionDelegate {
func session(
_ session: WCSession,
activationDidCompleteWith activationState: WCSessionActivationState,
error: Error?
) {
refreshState()
if let error {
print("WatchConnectivity activation failed: \(error.localizedDescription)")
}else{
transferLoginInfo(userInfo: AppShared.shared.myUserInfo)
}
}
func sessionDidBecomeInactive(_ session: WCSession) {
refreshState()
}
func sessionDidDeactivate(_ session: WCSession) {
refreshState()
session.activate()
}
func sessionReachabilityDidChange(_ session: WCSession) {
refreshState()
if session.isReachable {
_ = sendLoginInfoMessage(userInfo: AppShared.shared.myUserInfo)
}
}
func session(_ session: WCSession, didReceiveMessage message: [String: Any]) {
if message["command"] as? String == AppGroupMessageKey.watchDeviceToken,
let token = message["token"] as? String {
AppGroupConstants.defaults?.set(token, forKey: AppGroupConstants.Key.watchDeviceToken)
Task {
await AppShared.shared.reportDeviceInfo()
}
}
}
func session(
_ session: WCSession,
didReceiveMessage message: [String: Any],
replyHandler: @escaping ([String: Any]) -> Void
) {
if message["command"] as? String == AppGroupMessageKey.requestLoginState {
let userInfo = AppShared.shared.myUserInfo
var reply = loginPayload(userInfo: userInfo)
if let userInfo, let json = userInfo.jsonString {
reply["json"] = json
}
replyHandler(reply)
} else if message["command"] as? String == AppGroupMessageKey.watchDeviceToken,
let token = message["token"] as? String {
AppGroupConstants.defaults?.set(token, forKey: AppGroupConstants.Key.watchDeviceToken)
Task {
await AppShared.shared.reportDeviceInfo()
}
replyHandler(["success": true])
} else if message["command"] as? String == AppGroupMessageKey.statusPulseRefresh {
replyHandler(["success": true])
} else {
replyHandler(["success": true])
}
}
}