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

SwiftUI用@UIApplicationDelegateAdaptor时推送注册方法未调用如何解决

核心问题排查方向
  • 未正确申请推送权限:必须先向用户申请通知显示权限,权限通过后再发起远程推送注册请求,否则系统会直接静默拒绝注册,不会触发令牌回调
  • AppDelegate绑定格式错误:需确保AppDelegate同时继承NSObject、遵守UIApplicationDelegate协议,@UIApplicationDelegateAdaptor绑定声明要放在SwiftUI入口App结构体的属性位置
  • 项目能力配置缺失:未在项目Signing & Capabilities中添加Push Notifications能力,或证书未配置推送权限,都会导致注册请求失败
正确实现方案

1. 完整实现AppDelegate逻辑

import UserNotifications

class AppDelegate: NSObject, UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        // 先申请通知权限
        let notifyCenter = UNUserNotificationCenter.current()
        notifyCenter.requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
            guard granted, error == nil else {
                // 权限被拒绝直接返回,不需要发起注册
                return
            }
            // 权限申请通过后,主线程发起远程推送注册
            DispatchQueue.main.async {
                UIApplication.shared.registerForRemoteNotifications()
            }
        }
        return true
    }
    
    // 推送注册成功,拿到设备令牌
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        // 把Data类型的令牌转换为字符串即可使用
        let tokenStr = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
        print("设备推送令牌:\(tokenStr)")
    }
    
    // 推送注册失败,必须实现这个方法排查错误原因
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("推送注册失败:\(error.localizedDescription)")
    }
}

2. 绑定AppDelegate到SwiftUI原生入口

不需要手动创建UIWindow切换回UIKit生命周期,直接用SwiftUI默认的App结构绑定即可,不会破坏环境对象的注入逻辑:

@main
struct YourProjectApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    
    var body: some Scene {
        WindowGroup {
            ContentView()
                .environmentObject(SessionStore())
        }
    }
}

3. 检查项目配置

  • 打开项目设置 -> Signing & Capabilities,确认已添加Push Notifications能力
  • 若需要后台接收推送,添加Background Modes能力,勾选Remote notifications选项
  • 确认当前使用的开发/发布证书已开启推送权限,证书配置错误也会导致注册直接失败
手动切换UIKit生命周期崩溃的原因

你手动创建UIWindow覆盖SwiftUI默认的生命周期逻辑,会导致SwiftUI的环境对象、状态对象的持有链路断裂,@ObservedObject、@EnvironmentObject修饰的对象会因为没有正确的作用域持有被提前释放,访问时就会触发野指针崩溃,用上述原生绑定方案即可避免该问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 14:27:03