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

SwiftUI点击推送启动App时didFinishLaunchingWithOptions无参数问题求助

解决App完全关闭时点击推送无法获取参数的问题

1. 正确从launchOptions中提取通知参数

在didFinishLaunchingWithOptions里,要通过iOS 10+的标准Key提取推送参数,别用旧版字符串Key,示例代码如下:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // 先完成推送注册(这一步必须前置,否则后续参数处理可能失效)
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
        if granted {
            DispatchQueue.main.async {
                application.registerForRemoteNotifications()
            }
        }
    }
    
    // 提取并处理推送参数
    if let remoteNotification = launchOptions?[.remoteNotification] as? [String: Any] {
        startWithNotification = true
        handleNotificationContent(remoteNotification) // 自定义的通知内容处理函数
    }
    
    return true
}

2. 适配系统回调顺序

App完全关闭时点击推送,系统会先触发didFinishLaunchingWithOptions,之后还会调用userNotificationCenter(_:didReceive:withCompletionHandler:)。如果你的startWithNotification变量没生效,可能是后续逻辑覆盖了变量值,或者处理时机不对,可以在这个回调里统一处理参数:

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    let userInfo = response.notification.request.content.userInfo
    handleNotificationContent(userInfo)
    completionHandler()
}

3. 检查推送Payload格式

确保后端发送的推送Payload符合APNs规范,必须包含aps核心字段,示例格式:

{
    "aps": {
        "alert": "测试推送内容",
        "sound": "default"
    },
    "customData": "你的自定义业务数据"
}

如果Payload格式不合法,系统不会将参数传入launchOptions。

4. 修正变量生命周期问题

检查startWithNotification的定义,必须作为AppDelegate的类属性存在,避免局部变量被销毁或意外重置:

class AppDelegate: UIResponder, UIApplicationDelegate {
    var startWithNotification = false // 作为类属性保证生命周期正确
    
    // ...其余代码
}

5. 规范测试流程

测试完全关闭状态时,必须彻底杀死App(从多任务界面划掉),而非仅后台挂起。后台挂起状态下点击推送,会直接走userNotificationCenter回调,不会触发didFinishLaunchingWithOptions。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 12:36:13