WatchAppDelegate.swift 2.45 KB
//
//  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)
    }
}