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

Swift & FCM:应用从后台切换至前台时如何获取推送通知数据?

Swift推送通知:后台直接打开App获取数据解决方案

我来帮你搞定这个场景的问题!当App处于后台,用户直接打开而不是点击通知横幅时,推送数据确实不会走UNUserNotificationCenter的回调,得从App启动或唤醒的入口去拿。下面分情况给你具体实现方案:

1. 区分冷启动和后台唤醒的处理逻辑

iOS 13+(SceneDelegate 场景)

如果你的App用了SceneDelegate,在scene(_:willConnectTo:options:)里处理冷启动时的推送数据:

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    // 检查启动选项中是否包含远程通知
    if let remoteNotification = connectionOptions.remoteNotification {
        self.handlePushNotification(userInfo: remoteNotification)
    }
    
    // 其他App初始化代码...
}

// 后台唤醒时的回调
func scene(_ scene: UIScene, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    self.handlePushNotification(userInfo: userInfo)
    completionHandler(.newData) // 根据实际情况返回结果
}

// 封装统一的推送处理方法
private func handlePushNotification(userInfo: [AnyHashable: Any]) {
    print("获取到推送数据:\(userInfo)")
    // 这里写你的业务逻辑,比如解析payload、跳转页面等
}

iOS 12及以下(AppDelegate 场景)

如果是老版本的AppDelegate架构,在didFinishLaunchingWithOptions和didReceiveRemoteNotification里处理:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // 冷启动时检查推送数据
    if let remoteNotification = launchOptions?[.remoteNotification] as? [AnyHashable: Any] {
        self.handlePushNotification(userInfo: remoteNotification)
    }
    
    // 其他初始化代码...
    return true
}

// 后台唤醒时的回调
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    self.handlePushNotification(userInfo: userInfo)
    completionHandler(.newData)
}

private func handlePushNotification(userInfo: [AnyHashable: Any]) {
    print("获取到推送数据:\(userInfo)")
    // 处理推送逻辑
}

2. 关键配置注意事项

  • 推送Payload必须包含content-available: 1:这是让苹果在后台把推送给App的关键字段,示例payload如下:
{
    "aps": {
        "alert": "你的推送内容",
        "badge": 1,
        "sound": "default",
        "content-available": 1
    },
    "custom_data": "你的自定义数据"
}
  • 开启后台远程通知权限:在Xcode中,进入项目的Signing & Capabilities,添加Background Modes并勾选Remote notifications选项。

这样配置后,不管用户是点击通知横幅打开App,还是直接从后台/桌面启动App,你都能正常获取到推送的相关数据啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 20:28:17