You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在watchOS的SwiftUI中注册推送通知并配置相关回调?

推送通知设置与回调实现方案

在SwiftUI的App结构体中,没有直接对应的applicationDidFinishLaunching方法,但可以通过关联自定义UIApplicationDelegate来实现传统UIKit中的生命周期逻辑和推送通知回调,具体方案如下:

步骤1:实现自定义UIApplicationDelegate

创建一个同时遵循UIApplicationDelegate和UNUserNotificationCenterDelegate的类,集中处理推送授权、远程注册和通知回调:

import UIKit
import UserNotifications

class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // 对应applicationDidFinishLaunching的初始化逻辑
        setupPushNotifications()
        return true
    }
    
    private func setupPushNotifications() {
        // 设置通知中心代理,确保能收到回调
        UNUserNotificationCenter.current().delegate = self
        
        // 请求用户通知授权
        UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .sound, .alert]) { granted, error in
            if let error = error {
                print("通知授权请求失败:\(error.localizedDescription)")
            }
            if granted {
                // 授权成功后,注册远程通知以获取Device Token
                DispatchQueue.main.async {
                    UIApplication.shared.registerForRemoteNotifications()
                }
            }
        }
    }
    
    // 远程通知注册成功,获取Device Token
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let tokenString = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
        print("Device Token:\(tokenString)")
        // 此处可将Token上传至你的服务器
    }
    
    // 远程通知注册失败
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("远程通知注册失败:\(error.localizedDescription)")
    }
    
    // 前台收到通知时的回调,配置通知展示方式
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        // 设置前台显示通知的选项,比如横幅、声音、角标
        completionHandler([.banner, .sound, .badge])
    }
    
    // 用户点击通知后的回调,处理交互逻辑
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        let notificationInfo = response.notification.request.content.userInfo
        print("用户点击通知,携带信息:\(notificationInfo)")
        
        // 处理完业务逻辑后必须调用completionHandler
        completionHandler()
    }
}

步骤2:在App结构体中关联自定义Delegate

修改你的FieldService_Watch_AppApp,通过UIApplicationDelegateAdaptor属性绑定上面的AppDelegate:

import SwiftUI
import UserNotifications

@main
struct FieldService_Watch_AppApp: App {
    // 关联自定义AppDelegate
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    
    @Environment(.scenePhase) private var scenePhase
    
    var body: some Scene {
        WindowGroup {
            TabView {
                TimerView()
                ContentView()
                CategoriesView()
                    .environment(.managedObjectContext, manager.defaultContext)
                ServicesView()
                    .environment(.managedObjectContext, manager.defaultContext)
                FirstView()
            }
            .tabViewStyle(PageTabViewStyle())
        }
        .onChange(of: scenePhase) { phase in
            if case .active = phase {
                Task {
                    await loadData()
                }
            }
        }
    }

    private func loadData() async {
        // 保留你原本的场景激活时的业务逻辑即可,推送授权已在AppDelegate中处理
    }
}

关键说明

  • 推送授权时机:放在applicationDidFinishLaunching中是最优选择,App启动时即可完成授权请求,无需等待场景激活。
  • 远程通知注册:必须在用户授权通知后,才能调用registerForRemoteNotifications()获取Device Token,这是APNs推送的必要前提。
  • 通知回调处理:通过UNUserNotificationCenterDelegate的两个核心方法,分别控制前台通知展示规则和用户点击后的交互逻辑。

内容的提问来源于stack exchange,提问作者kunass2

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 09:06:37