-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWatchCommunication.swift
196 lines (169 loc) · 6.3 KB
/
WatchCommunication.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
//
// WatchCommunication.swift
// expenseTracker
//
// Created by Mason on 6/10/23.
//
import Foundation
import WatchConnectivity
import Combine
import CoreData
struct SerializedExpense: Codable {
let amount: Float
let desc: String
let date: Date
let categoryId: String
}
struct SerializedCategory: Codable, Identifiable {
let id: String
let name: String
}
class WatchSessionDelegate: NSObject, WCSessionDelegate {
//init() {
//super.init()
//}
private var session: WCSession?
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
self.session = session
}
#if os(iOS)
// more boilerplate needed for ios
func sessionDidBecomeInactive(_ session: WCSession) {
}
func sessionDidDeactivate(_ session: WCSession) {
// i think we need to do this to activate the new session with the other apple watch?
session.activate()
}
// ios app receives messages
let dataSubject: PassthroughSubject<SerializedExpense, Never>
init(_ dataSubject: PassthroughSubject<SerializedExpense, Never>) {
self.dataSubject = dataSubject
super.init()
}
func session(_ session: WCSession, didReceiveMessage message: [String : Any]) {
DispatchQueue.main.async {
// try to decode as serializedexpense
if let expenseData = message["expense"] as? Data {
let decoder = JSONDecoder()
if let expense = try? decoder.decode(SerializedExpense.self, from: expenseData) {
// broadcast this update
self.dataSubject.send(expense)
} else {
print("some sort of communication error :(")
}
} else {
print("some sort of communication error :(")
}
}
}
// ios app sends application contexts
func sendCategories(_ categories: [ExpenseCategory]) {
var serializedCategories = [SerializedCategory]()
for category in categories {
serializedCategories.append(SerializedCategory(id: category.objectID.uriRepresentation().absoluteString, name: category.displayName ?? ""))
}
let encoder = JSONEncoder()
if let encodedData = try? encoder.encode(serializedCategories) {
if let _ = try? session?.updateApplicationContext(["categories": encodedData]) {
} else {
print("failed to send data to watch")
}
}
}
#else
// watchos app receives application contexts
let dataSubject: CurrentValueSubject<[SerializedCategory], Never>
init(_ dataSubject: CurrentValueSubject<[SerializedCategory], Never>) {
self.dataSubject = dataSubject
super.init()
}
func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String : Any]) {
DispatchQueue.main.async {
if let categoriesData = applicationContext["categories"] as? Data {
// try decode
let decoder = JSONDecoder()
if let categories = try? decoder.decode([SerializedCategory].self, from: categoriesData) {
// decode succeeded!
self.dataSubject.send(categories)
// also store the data in UserDefaults
UserDefaults.standard.set(categoriesData, forKey: "categories")
} else {
print("some sort of communication error :(")
}
} else {
print("some sort of communication error :(")
}
}
}
// watchos app sends messages
func sendExpense(_ expense: SerializedExpense) {
let encoder = JSONEncoder()
if let encodedData = try? encoder.encode(expense) {
session?.sendMessage(["expense": encodedData], replyHandler: nil) { error in
// TODO: bubble this up to the user in some way
print(error.localizedDescription)
}
}
}
#endif
}
#if os(iOS)
class CommunicationManager: ObservableObject {
var session: WCSession?
let delegate: WatchSessionDelegate?
let dataSubject = PassthroughSubject<SerializedExpense, Never>()
@Published private(set) var initializedSucessfully: Bool = false
init(session: WCSession = .default) {
if WCSession.isSupported() {
let delegate = WatchSessionDelegate(dataSubject)
self.session = session
self.delegate = delegate
session.delegate = delegate
session.activate()
self.initializedSucessfully = true
} else {
self.session = nil
self.delegate = nil
self.initializedSucessfully = false
}
}
public func syncCategories(_ categories: [ExpenseCategory]) {
self.delegate?.sendCategories(categories)
}
}
#else
class CommunicationManager: ObservableObject {
var session: WCSession?
let delegate: WatchSessionDelegate?
let dataSubject = CurrentValueSubject<[SerializedCategory], Never>([])
@Published private(set) var initializedSucessfully: Bool = false
@Published private(set) var categories: [SerializedCategory] = []
init(session: WCSession = .default) {
if WCSession.isSupported() {
let delegate = WatchSessionDelegate(dataSubject)
self.session = session
self.delegate = delegate
session.delegate = delegate
session.activate()
self.initializedSucessfully = true
} else {
self.session = nil
self.delegate = nil
self.initializedSucessfully = false
}
dataSubject
.receive(on: DispatchQueue.main)
.assign(to: &$categories)
// try decode categories
let decoder = JSONDecoder()
if let categoriesData = UserDefaults.standard.data(forKey: "categories"),
let categories = try? decoder.decode([SerializedCategory].self, from: categoriesData) {
// decode succeeded!
dataSubject.send(categories)
}
}
func sendExpense(_ expense: SerializedExpense) {
self.delegate?.sendExpense(expense)
}
}
#endif