forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAppDelegate.swift
More file actions
702 lines (616 loc) · 29.6 KB
/
Copy pathAppDelegate.swift
File metadata and controls
702 lines (616 loc) · 29.6 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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
import UIKit
import Flutter
import UserNotifications
import app_links
import WatchConnectivity
import AVFoundation
import Speech
import WidgetKit
extension FlutterError: Error {}
// MARK: - Quick Actions Icon Patcher
/// Observes UIApplication.shortcutItems via KVO and replaces template-image icons
/// (set by the quick_actions Flutter plugin) with native SF Symbol icons.
final class QuickActionsIconPatcher: NSObject {
static let shared = QuickActionsIconPatcher()
private var isObserving = false
private let symbolMap: [String: String] = [
"add_task": "checkmark.circle.fill",
"ask_omi": "message.fill",
"voice_mode": "waveform",
"mute": "mic.slash.fill",
"unmute": "mic.fill",
"connect_device": "cable.connector.horizontal",
"device_settings": "slider.horizontal.3",
]
func startObserving() {
guard !isObserving else { return }
UIApplication.shared.addObserver(
self,
forKeyPath: #keyPath(UIApplication.shortcutItems),
options: [.new],
context: nil
)
isObserving = true
}
func stopObserving() {
guard isObserving else { return }
UIApplication.shared.removeObserver(self, forKeyPath: #keyPath(UIApplication.shortcutItems))
isObserving = false
}
override func observeValue(
forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey: Any]?,
context: UnsafeMutableRawPointer?
) {
guard keyPath == #keyPath(UIApplication.shortcutItems) else { return }
DispatchQueue.main.async { self.patchIcons() }
}
private func patchIcons() {
guard let items = UIApplication.shared.shortcutItems, !items.isEmpty else { return }
let patched = items.map { item -> UIApplicationShortcutItem in
guard let symbol = symbolMap[item.type] else { return item }
let icon = UIApplicationShortcutIcon(systemImageName: symbol)
return UIApplicationShortcutItem(
type: item.type,
localizedTitle: item.localizedTitle,
localizedSubtitle: item.localizedSubtitle,
icon: icon,
userInfo: item.userInfo
)
}
// Stop observing before setting to avoid infinite KVO loop.
stopObserving()
UIApplication.shared.shortcutItems = patched
startObserving()
}
deinit { stopObserving() }
}
@main
@objc class AppDelegate: FlutterAppDelegate {
private var methodChannel: FlutterMethodChannel?
private var appleRemindersChannel: FlutterMethodChannel?
private var appleHealthChannel: FlutterMethodChannel?
private let appleRemindersService = AppleRemindersService()
private let appleHealthService = AppleHealthService()
private var phoneMicController: PhoneMicController?
private var notificationTitleOnKill: String?
private var notificationBodyOnKill: String?
var session: WCSession?
var flutterWatchAPI: WatchRecorderFlutterAPI?
var rayBanMetaHostApi: RayBanMetaHostApiImpl?
private var audioChunks: [Int: (Data, Double)] = [:] // (audioData, sampleRate)
private var nextExpectedChunkIndex: Int = 0
private var isRecordingActive: Bool = false // Track recording state to handle app restarts
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GeneratedPluginRegistrant.register(with: self)
QuickActionsIconPatcher.shared.startObserving()
if WCSession.isSupported() {
session = WCSession.default
session?.delegate = self
session?.activate();
let controller = window?.rootViewController as? FlutterViewController
flutterWatchAPI = WatchRecorderFlutterAPI(binaryMessenger: controller!.binaryMessenger)
let api: WatchRecorderHostAPI = RecorderHostApiImpl(session: session!, flutterWatchAPI: flutterWatchAPI)
WatchRecorderHostAPISetup.setUp(binaryMessenger: controller!.binaryMessenger, api: api)
}
// Native BLE module — register Pigeon APIs
NSLog("[OmiBle] Registering BLE Pigeon APIs")
let bleController = window?.rootViewController as? FlutterViewController
if let messenger = bleController?.binaryMessenger {
let bleFlutterApi = BleFlutterApi(binaryMessenger: messenger)
OmiBleManager.shared.setFlutterApi(bleFlutterApi)
let bleHostApi = BleHostApiImpl(bleManager: OmiBleManager.shared)
BleHostApiSetup.setUp(binaryMessenger: messenger, api: bleHostApi)
NSLog("[OmiBle] BLE Pigeon APIs registered successfully")
} else {
NSLog("[OmiBle] ERROR: Could not get FlutterBinaryMessenger")
}
// Ray-Ban Meta (Meta Wearables DAT camera + Bluetooth HFP mic) — Pigeon APIs.
// Registered unconditionally; the impl reports availability mode based on
// whether the DAT SDK is linked into this build.
if let messenger = (window?.rootViewController as? FlutterViewController)?.binaryMessenger {
let rayBanFlutterApi = RayBanMetaFlutterAPI(binaryMessenger: messenger)
let rayBanApi = RayBanMetaHostApiImpl(flutterAPI: rayBanFlutterApi)
rayBanMetaHostApi = rayBanApi
RayBanMetaHostAPISetup.setUp(binaryMessenger: messenger, api: rayBanApi)
}
// Native phone-mic capture (conversation recording) — Pigeon APIs.
// Self-healing AVAudioEngine capture; interruption/route recovery is
// handled natively, Dart only mirrors the state.
if let messenger = (window?.rootViewController as? FlutterViewController)?.binaryMessenger {
let phoneMicFlutterApi = PhoneMicFlutterApi(binaryMessenger: messenger)
let controller = PhoneMicController(flutterApi: phoneMicFlutterApi)
phoneMicController = controller
PhoneMicHostApiSetup.setUp(binaryMessenger: messenger, api: PhoneMicHostApiImpl(controller: controller))
}
// Retrieve the link from parameters
if let url = AppLinks.shared.getLink(launchOptions: launchOptions) {
// We have a link, propagate it to your Flutter app or not
AppLinks.shared.handleLink(url: url)
return true // Returning true will stop the propagation to other packages
}
//Creates a method channel to handle notifications on kill
let controller = window?.rootViewController as? FlutterViewController
methodChannel = FlutterMethodChannel(name: "com.friend.ios/notifyOnKill", binaryMessenger: controller!.binaryMessenger)
methodChannel?.setMethodCallHandler { [weak self] (call, result) in
self?.handleMethodCall(call, result: result)
}
// Create Apple Reminders method channel
appleRemindersChannel = FlutterMethodChannel(name: "com.omi.apple_reminders", binaryMessenger: controller!.binaryMessenger)
appleRemindersChannel?.setMethodCallHandler { [weak self] (call, result) in
self?.handleAppleRemindersCall(call, result: result)
}
// Create Apple Health method channel
appleHealthChannel = FlutterMethodChannel(name: "com.omi.apple_health", binaryMessenger: controller!.binaryMessenger)
appleHealthChannel?.setMethodCallHandler { [weak self] (call, result) in
self?.handleAppleHealthCall(call, result: result)
}
// Create Speech Recognition method channel
let speechChannel = FlutterMethodChannel(name: "com.omi.ios/speech", binaryMessenger: controller!.binaryMessenger)
let speechHandler = SpeechRecognitionHandler()
speechChannel.setMethodCallHandler { (call, result) in
speechHandler.handle(call, result: result)
}
// TestFlight environment detection
let envChannel = FlutterMethodChannel(name: "com.omi/environment", binaryMessenger: controller!.binaryMessenger)
envChannel.setMethodCallHandler { (call, result) in
if call.method == "isTestFlight" {
let isTestFlight = Bundle.main.appStoreReceiptURL?.lastPathComponent == "sandboxReceipt"
result(isTestFlight)
} else {
result(FlutterMethodNotImplemented)
}
}
// Audio session configuration for Bluetooth microphone support
let audioSessionChannel = FlutterMethodChannel(name: "com.omi.ios/audioSession", binaryMessenger: controller!.binaryMessenger)
audioSessionChannel.setMethodCallHandler { (call, result) in
if call.method == "configureForBluetooth" {
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(
.playAndRecord,
mode: .default,
options: [.allowBluetooth, .allowBluetoothA2DP, .defaultToSpeaker]
)
try audioSession.setActive(true)
result(true)
} catch {
result(FlutterError(code: "AUDIO_SESSION_ERROR", message: error.localizedDescription, details: nil))
}
} else {
result(FlutterMethodNotImplemented)
}
}
// Create WiFi Network plugin for device AP connection
_ = WifiNetworkPlugin(messenger: controller!.binaryMessenger)
// Battery widget channel — writes Omi device battery to the shared App Group
// so the WidgetKit extension can read it.
let batteryWidgetChannel = FlutterMethodChannel(name: "com.omi.battery_widget", binaryMessenger: controller!.binaryMessenger)
batteryWidgetChannel.setMethodCallHandler { (call, result) in
let defaults = UserDefaults(suiteName: "group.com.friend-app-with-wearable.ios12")
guard let args = call.arguments as? [String: Any] else {
result(FlutterMethodNotImplemented)
return
}
switch call.method {
case "updateBatteryInfo":
defaults?.set(args["deviceName"] as? String ?? "Omi", forKey: "widget_device_name")
defaults?.set(args["batteryLevel"] as? Int ?? -1, forKey: "widget_battery_level")
defaults?.set(args["deviceType"] as? String ?? "omi", forKey: "widget_device_type")
defaults?.set(args["isConnected"] as? Bool ?? false, forKey: "widget_is_connected")
defaults?.set(Date(), forKey: "widget_last_updated")
// NOTE: isMuted is intentionally NOT written here — only updateMuteState controls it
if #available(iOS 14.0, *) {
WidgetCenter.shared.reloadTimelines(ofKind: "OmiBatteryWidget")
}
case "updateMuteState":
let isMuted = (args["isMuted"] as? Bool) ?? (args["isMuted"] as? NSNumber)?.boolValue ?? false
defaults?.set(isMuted, forKey: "widget_is_muted")
if #available(iOS 14.0, *) {
WidgetCenter.shared.reloadAllTimelines()
}
default:
result(FlutterMethodNotImplemented)
return
}
result(nil)
}
// Register Phone Calls plugin
OmiPhoneCallsPlugin.register(with: self.registrar(forPlugin: "OmiPhoneCallsPlugin")!)
// here, Without this code the task will not work.
SwiftFlutterForegroundTaskPlugin.setPluginRegistrantCallback { registry in
GeneratedPluginRegistrant.register(with: registry)
}
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
}
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
// Meta AI app calls back into this app to finish Ray-Ban Meta registration
// (AppLinkURLScheme in the MWDAT Info.plist dictionary).
override func application(
_ app: UIApplication,
open url: URL,
options: [UIApplication.OpenURLOptionsKey: Any] = [:]
) -> Bool {
if rayBanMetaHostApi?.handleUrl(url) == true {
return true
}
return super.application(app, open: url, options: options)
}
private func handleMethodCall(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
switch call.method {
case "setNotificationOnKillService":
handleSetNotificationOnKillService(call: call)
default:
result(FlutterMethodNotImplemented)
}
}
private func handleSetNotificationOnKillService(call: FlutterMethodCall) {
NSLog("handleMethodCall: setNotificationOnKillService")
if let args = call.arguments as? Dictionary<String, Any> {
notificationTitleOnKill = args["title"] as? String
notificationBodyOnKill = args["description"] as? String
}
}
private func handleAppleRemindersCall(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
appleRemindersService.handleMethodCall(call, result: result)
}
private func handleAppleHealthCall(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
appleHealthService.handleMethodCall(call, result: result)
}
// MARK: - Silent Push for Apple Reminders Auto-Sync
override func application(
_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void
) {
// Check if it's Apple Reminders sync
if let type = userInfo["type"] as? String, type == "apple_reminders_sync" {
handleAppleRemindersSync(userInfo: userInfo, completionHandler: completionHandler)
return
}
// Also check nested under "data" key (some FCM configurations)
if let data = userInfo["data"] as? [String: Any],
let type = data["type"] as? String,
type == "apple_reminders_sync" {
handleAppleRemindersSync(userInfo: data, completionHandler: completionHandler)
return
}
super.application(application, didReceiveRemoteNotification: userInfo, fetchCompletionHandler: completionHandler)
}
private func handleAppleRemindersSync(
userInfo: [AnyHashable: Any],
completionHandler: @escaping (UIBackgroundFetchResult) -> Void
) {
guard let itemsJson = userInfo["items"] as? String else {
completionHandler(.failed)
return
}
let exportedMappings = appleRemindersService.syncBatchFromJSON(itemsJson)
if !exportedMappings.isEmpty {
DispatchQueue.main.async {
self.appleRemindersChannel?.invokeMethod("markExportedBatch", arguments: ["mappings": exportedMappings])
}
}
completionHandler(exportedMappings.isEmpty ? .noData : .newData)
}
override func applicationWillEnterForeground(_ application: UIApplication) {
super.applicationWillEnterForeground(application)
OmiBleManager.shared.reconnectStalePeripherals()
}
override func applicationWillTerminate(_ application: UIApplication) {
QuickActionsIconPatcher.shared.stopObserving()
OmiBleManager.shared.disconnectAllPeripherals()
// If title and body are nil, then we don't need to show notification.
if notificationTitleOnKill == nil || notificationBodyOnKill == nil {
return
}
let content = UNMutableNotificationContent()
content.title = notificationTitleOnKill!
content.body = notificationBodyOnKill!
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
let request = UNNotificationRequest(identifier: "notification on app kill", content: content, trigger: trigger)
NSLog("Running applicationWillTerminate")
UNUserNotificationCenter.current().add(request) { (error) in
if let error = error {
NSLog("Failed to show notification on kill service => error: \(error.localizedDescription)")
} else {
NSLog("Show notification on kill now")
}
}
}
private func handleAudioChunk(_ message: [String: Any]) {
guard isRecordingActive else {
print("Ignoring audio chunk - recording not active") // probably started recording with main omi app closed
return
}
guard let audioChunk = message["audioChunk"] as? Data,
let chunkIndex = message["chunkIndex"] as? Int,
let isLast = message["isLast"] as? Bool,
let sampleRate = message["sampleRate"] as? Double else {
return
}
audioChunks[chunkIndex] = (audioChunk, sampleRate)
if isLast {
reassembleAndSendAudioData()
} else {
// Prepend 3 dummy bytes so downstream can uniformly strip headers
var prefixedChunk = Data([0x00, 0x00, 0x00])
prefixedChunk.append(audioChunk)
let flutterData = FlutterStandardTypedData(bytes: prefixedChunk)
self.flutterWatchAPI?.onAudioChunk(audioChunk: flutterData, chunkIndex: Int64(chunkIndex), isLast: isLast, sampleRate: sampleRate) { result in
switch result {
case .success:
break
case .failure(let error):
print("Audio chunk \(chunkIndex) sent to Flutter - Error: \(error.message)")
}
}
}
}
private func reassembleAndSendAudioData() {
// Sort chunks by index and combine them
let sortedChunks = audioChunks.sorted(by: { $0.key < $1.key })
var combinedData = Data()
var sampleRate: Double = 48000.0 // Default fallback
for (_, chunkTuple) in sortedChunks {
let (chunkData, chunkSampleRate) = chunkTuple
combinedData.append(chunkData)
sampleRate = chunkSampleRate
}
// Prepend 3 dummy bytes for full buffer as well
var prefixed = Data([0x00, 0x00, 0x00])
prefixed.append(combinedData)
let flutterData = FlutterStandardTypedData(bytes: prefixed)
self.flutterWatchAPI?.onAudioData(audioData: flutterData) { result in
switch result {
case .success:
break
case .failure(let error):
print("Complete audio data sent to Flutter - Error: \(error.message)")
}
}
audioChunks.removeAll()
nextExpectedChunkIndex = 0
}
}
func registerPlugins(registry: FlutterPluginRegistry) {
GeneratedPluginRegistrant.register(with: registry)
}
extension AppDelegate: WCSessionDelegate {
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) { }
func sessionDidBecomeInactive(_ session: WCSession) {
print("Session Watch Become Inactive")
}
func sessionDidDeactivate(_ session: WCSession) {
print("Session Watch Deactivate")
}
// Receive a message from watch (foreground/active)
func session(_ session: WCSession, didReceiveMessage message: [String : Any]) {
Task {
guard let method = message["method"] as? String else {
return
}
switch method {
case "startRecording":
self.isRecordingActive = true
self.audioChunks.removeAll()
self.nextExpectedChunkIndex = 0
DispatchQueue.main.async {
self.flutterWatchAPI?.onRecordingStarted() { result in
switch result {
case .success:
break
case .failure(let error):
print("iOS: Recording started notification sent to Flutter - Error: \(error.message)")
}
}
}
case "stopRecording":
self.isRecordingActive = false
self.flutterWatchAPI?.onRecordingStopped() { result in
switch result {
case .success:
break
case .failure(let error):
print("Recording stopped on Flutter - Error: \(error.message)")
}
}
case "sendAudioData":
if let audioData = message["audioData"] as? Data {
// Prepend 3 dummy bytes for single-shot audio data
var prefixed = Data([0x00, 0x00, 0x00])
prefixed.append(audioData)
let flutterData = FlutterStandardTypedData(bytes: prefixed)
self.flutterWatchAPI?.onAudioData(audioData: flutterData) { result in
switch result {
case .success:
break
case .failure(let error):
print("Audio data sent to Flutter - Error: \(error.message)")
}
}
} else {
print("Failed to cast audioData as Data - received type: \(type(of: message["audioData"]))")
}
case "sendAudioChunk":
self.handleAudioChunk(message)
case "recordingError":
if let error = message["error"] as? String {
self.flutterWatchAPI?.onRecordingError(error: error) { result in
switch result {
case .success:
break
case .failure(let error):
print("Recording error sent to Flutter - Error: \(error.message)")
}
}
}
case "microphonePermissionResult":
if let granted = message["granted"] as? Bool {
self.flutterWatchAPI?.onMicrophonePermissionResult(granted: granted) { result in
switch result {
case .success:
break
case .failure(let error):
print("Microphone permission result sent to Flutter - Error: \(error.message)")
}
}
}
case "batteryUpdate":
if let batteryLevel = message["batteryLevel"] as? Double,
let batteryState = message["batteryState"] as? Int {
UserDefaults.standard.set(batteryLevel, forKey: "watch_battery_level")
UserDefaults.standard.set(batteryState, forKey: "watch_battery_state")
UserDefaults.standard.set(Date(), forKey: "watch_battery_last_updated")
DispatchQueue.main.async {
self.flutterWatchAPI?.onWatchBatteryUpdate(batteryLevel: batteryLevel, batteryState: Int64(batteryState)) { result in
switch result {
case .success:
break
case .failure(let error):
print("iOS: Battery update sent to Flutter - Error: \(error.message)")
}
}
}
}
case "watchInfoUpdate":
if let name = message["name"] as? String,
let model = message["model"] as? String,
let systemVersion = message["systemVersion"] as? String,
let localizedModel = message["localizedModel"] as? String {
UserDefaults.standard.set(name, forKey: "watch_device_name")
UserDefaults.standard.set(model, forKey: "watch_device_model")
UserDefaults.standard.set(systemVersion, forKey: "watch_system_version")
UserDefaults.standard.set(localizedModel, forKey: "watch_localized_model")
UserDefaults.standard.set(Date(), forKey: "watch_info_last_updated")
}
default:
print("Unknown method: \(method)")
}
}
}
// Receive user info from watch (background/offline)
// Used for 1.5 second audio chunks when screen is off or app is backgrounded
func session(_ session: WCSession, didReceiveUserInfo userInfo: [String : Any]) {
Task {
guard let method = userInfo["method"] as? String else {
return
}
switch method {
case "sendAudioChunk":
self.handleAudioChunk(userInfo)
case "stopRecording":
self.isRecordingActive = false
self.flutterWatchAPI?.onRecordingStopped() { result in
switch result {
case .success:
break
case .failure(let error):
print("Stop recording (background) sent to Flutter - Error: \(error.message)")
}
}
case "recordingError":
if let error = userInfo["error"] as? String {
self.flutterWatchAPI?.onRecordingError(error: error) { result in
switch result {
case .success:
break
case .failure(let error):
print("Recording error (background) sent to Flutter - Error: \(error.message)")
}
}
}
case "batteryUpdate":
if let batteryLevel = userInfo["batteryLevel"] as? Double,
let batteryState = userInfo["batteryState"] as? Int {
UserDefaults.standard.set(batteryLevel, forKey: "watch_battery_level")
UserDefaults.standard.set(batteryState, forKey: "watch_battery_state")
UserDefaults.standard.set(Date(), forKey: "watch_battery_last_updated")
DispatchQueue.main.async {
self.flutterWatchAPI?.onWatchBatteryUpdate(batteryLevel: batteryLevel, batteryState: Int64(batteryState)) { result in
switch result {
case .success:
break
case .failure(let error):
print("iOS: Background battery update sent to Flutter - Error: \(error.message)")
}
}
}
}
case "watchInfoUpdate":
if let name = userInfo["name"] as? String,
let model = userInfo["model"] as? String,
let systemVersion = userInfo["systemVersion"] as? String,
let localizedModel = userInfo["localizedModel"] as? String {
UserDefaults.standard.set(name, forKey: "watch_device_name")
UserDefaults.standard.set(model, forKey: "watch_device_model")
UserDefaults.standard.set(systemVersion, forKey: "watch_system_version")
UserDefaults.standard.set(localizedModel, forKey: "watch_localized_model")
UserDefaults.standard.set(Date(), forKey: "watch_info_last_updated")
}
default:
print("Unknown background method: \(method)")
}
}
}
}
class SpeechRecognitionHandler: NSObject {
func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
if call.method == "transcribe" {
guard let args = call.arguments as? [String: Any],
let path = args["filePath"] as? String else {
result(FlutterError(code: "INVALID_ARGS", message: "Missing arguments", details: nil))
return
}
let language = args["language"] as? String ?? "en-US"
transcribe(filePath: path, language: language, result: result)
} else {
result(FlutterMethodNotImplemented)
}
}
private func transcribe(filePath: String, language: String, result: @escaping FlutterResult) {
// Request authorization first
SFSpeechRecognizer.requestAuthorization { authStatus in
if authStatus != .authorized {
result(FlutterError(code: "UNAUTHORIZED", message: "Speech recognition not authorized", details: nil))
return
}
let fileUrl = URL(fileURLWithPath: filePath)
let localeIdentifier = language.isEmpty ? "en-US" : language
let locale = Locale(identifier: localeIdentifier)
guard let recognizer = SFSpeechRecognizer(locale: locale) else {
result(FlutterError(code: "UNAVAILABLE", message: "Speech recognizer not available for locale \(localeIdentifier)", details: nil))
return
}
if !recognizer.isAvailable {
result(FlutterError(code: "UNAVAILABLE", message: "Speech recognizer service is currently unavailable", details: nil))
return
}
let request = SFSpeechURLRecognitionRequest(url: fileUrl)
request.shouldReportPartialResults = false
request.requiresOnDeviceRecognition = true // Force on-device
let task = recognizer.recognitionTask(with: request) { (recognitionResult, error) in
if let error = error {
// Check if it's just "No speech identified" which might happen with silence
let nsError = error as NSError
if nsError.domain == "kAFAssistantErrorDomain" && nsError.code == 1110 {
result("") // Treat as empty
} else {
result(FlutterError(code: "RECOGNITION_ERROR", message: error.localizedDescription, details: nil))
}
return
}
if let recognitionResult = recognitionResult, recognitionResult.isFinal {
let text = recognitionResult.bestTranscription.formattedString
result(text)
}
}
}
}
}