WatchAppDelegate.swift
2.45 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
//
// WatchAppDelegate.swift
// Runner Watch App
//
// Created by 权海 on 2026/6/17.
//
import WatchKit
import UserNotifications
final class WatchAppDelegate: NSObject, WKApplicationDelegate, UNUserNotificationCenterDelegate {
func applicationDidFinishLaunching() {
setup()
let center = UNUserNotificationCenter.current()
center.delegate = self
requestNotificationPermission()
}
private func setup(){
WatchUserAgent.share.genUA()
WatchSessionManager.share.addListen()
WatchDataManager.share.requestAuthForHealth()
WatchDataManager.share.fetchMyTodayData()
WatchDataManager.share.fetchOtherTodayData()
ThinkSDKUtil.initSDK()
if let id = WatchUserinfoManager.share.myUserinfo?.id {
ThinkSDKUtil.login(id)
}
}
private func requestNotificationPermission() {
UNUserNotificationCenter.current().requestAuthorization(
options: [.alert, .sound, .badge]
) { granted, error in
print("watch notification permission:", granted, error as Any)
guard granted else { return }
DispatchQueue.main.async {
WKApplication.shared().registerForRemoteNotifications()
}
}
}
func didRegisterForRemoteNotifications(withDeviceToken deviceToken: Data) {
let token = deviceToken.map { String(format: "%02x", $0) }.joined()
print("watch apns token:", token)
// TODO: 上传到你的服务端
// uploadWatchToken(token)
}
func didFailToRegisterForRemoteNotificationsWithError(_ error: Error) {
print("watch register push failed:", error)
}
// App 在前台收到通知:热启动前台展示
func userNotificationCenter(
_ center: UNUserNotificationCenter,
willPresent notification: UNNotification
) async -> UNNotificationPresentationOptions {
let userInfo = notification.request.content.userInfo
print("watch will present:", userInfo)
return [.banner, .sound]
}
// 用户点击通知:冷启动 / 后台 / 前台都走这里
func userNotificationCenter(
_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse
) async {
let userInfo = response.notification.request.content.userInfo
print("watch notification clicked:", userInfo)
WatchNotificationRouter.shared.handle(userInfo: userInfo)
}
}