首页  >  文章  >  后端开发  >  为什么 Firebase 云消息传递 (FCM) 通知在 iOS 上的后台模式下不保留?

为什么 Firebase 云消息传递 (FCM) 通知在 iOS 上的后台模式下不保留?

Susan Sarandon
Susan Sarandon原创
2024-10-20 15:22:02926浏览

Why Are Firebase Cloud Messaging (FCM) Notifications Not Retained in Background Mode on iOS?

Firebase 云消息传递 (FCM):当应用程序在 iOS 上处于后台模式时未收到通知

FCM 允许开发者将推送通知发送到iOS 和 Android 设备。当应用程序在后台时未收到通知时,就会出现此问题。

可能原因:

  • 发送通知的 PHP 代码不正确。
  • iOS 应用程序缺乏后台模式支持。

解决方案:

PHP 代码:

  • 将以下字段添加到您的 PHP 负载中:

    • 'content_available' =>; true(当 iOS 应用程序在后台时触发)
    • 'priority' => '高'
    • '通知'=> $data(将 $data 替换为您想要的通知数据)
  • 将 $data 设置为包含具有自定义值的“message”和“body”键。

iOS 应用程序:

  1. 检查 .gcm 文件是否包含在您的 Xcode 项目中。
  2. 确保 AppDelegate 符合 GCMReceiverDelegate。
  3. 重写 applicationDidBecomeActive 和 applicationDidEnterBackground 方法分别(重新)连接和断开与 FCM 的连接。
  4. 使用 UIRemoteNotificationType 注册通知。
  5. 实现 application:didReceiveRemoteNotification: 方法来处理收到的通知,甚至当应用程序在后台时。
  6. 如果需要,请实现 application:didReceiveRemoteNotification:fetchCompletionHandler: 方法以进一步处理在后台收到的通知。

更新的 PHP 代码:

<code class="php"><?php

$data = array(
    'message' => 'Hello World!',
    'body' => 'Hello World!'
);

$post = array(
    'registration_ids' => $ids,
    'data' => $data,
    'content_available' => true,
    'priority' => 'high',
    'notification' => $data
);

// ... Remaining code</code>

更新的 iOS 应用程序:

<code class="objc">// AppDelegate.h
@interface AppDelegate : UIResponder <UIApplicationDelegate, GCMReceiverDelegate>

// AppDelegate.m
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // ...
    // Register for remote notifications
    if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1) {
        UIRemoteNotificationType allNotificationTypes =
        (UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge);
        [application registerForRemoteNotificationTypes:allNotificationTypes];
    } else {
        UIUserNotificationType allNotificationTypes =
        (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
        UIUserNotificationSettings *settings =
        [UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    }
    // ...
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    [[GCMService sharedInstance] disconnect];
    _connectedToGCM = NO;
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    [[GCMService sharedInstance] connectWithHandler:^(NSError *error) {
        // ...
    }];
}

// ...</code>

注意:

  • 确保您已在 Apple 开发者门户中为您的应用启用推送通知。
  • 在 FCM 项目设置中添加推送通知证书。

以上是为什么 Firebase 云消息传递 (FCM) 通知在 iOS 上的后台模式下不保留?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn