【问题标题】:FCM notification is not working in iOS appFCM 通知在 iOS 应用程序中不起作用
【发布时间】:2016-05-31 06:28:00
【问题描述】:

我正在我的应用中集成 FCM 通知和云消息传递。我遵循了 Firebase 文档中提到的完全相同的步骤。即使我尝试过 FCM 给出的示例代码。它只是抛出一些警告:

<FIRInstanceID/WARNING> Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001 "The operation couldn’t be completed. and <FIRMessaging/WARNING> FIRMessaging registration is not ready with auth credentials.

我在 Appdelegate.m 中编写的代码是:

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

    // [START configure_firebase]
    [FIRApp configure];
    // [END configure_firebase]

    // Add observer for InstanceID token refresh callback.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tokenRefreshNotification:)
                                                 name:kFIRInstanceIDTokenRefreshNotification object:nil];
    return YES;
}

// [START receive_message]
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    // If you are receiving a notification message while your app is in the background,
    // this callback will not be fired till the user taps on the notification launching the application.
    // TODO: Handle data of notification

    // Print message ID.
    NSLog(@"Message ID: %@", userInfo[@"gcm.message_id"]);

    // Pring full message.
    NSLog(@"%@", userInfo);
}
// [END receive_message]

// [START refresh_token]
- (void)tokenRefreshNotification:(NSNotification *)notification {
    // Note that this callback will be fired everytime a new token is generated, including the first
    // time. So if you need to retrieve the token as soon as it is available this is where that
    // should be done.
    NSString *refreshedToken = [[FIRInstanceID instanceID] token];
    NSLog(@"InstanceID token: %@", refreshedToken);

    // Connect to FCM since connection may have failed when attempted before having a token.
    [self connectToFcm];

    // TODO: If necessary send token to appliation server.
}
// [END refresh_token]

// [START connect_to_fcm]
- (void)connectToFcm {
    [[FIRMessaging messaging] connectWithCompletion:^(NSError * _Nullable error) {
        if (error != nil) {
            NSLog(@"Unable to connect to FCM. %@", error);
        } else {
            NSLog(@"Connected to FCM.");
        }
    }];
}
// [END connect_to_fcm]

- (void)applicationDidBecomeActive:(UIApplication *)application {
    [self connectToFcm];
}

// [START disconnect_from_fcm]
- (void)applicationDidEnterBackground:(UIApplication *)application {
    [[FIRMessaging messaging] disconnect];
    NSLog(@"Disconnected from FCM");
}
// [END disconnect_from_fcm]

【问题讨论】:

  • 你是如何发送消息的?您是否使用 Firebase 控制台并针对所有设备?您是否添加了 GoogleService-Info.plist?您也可以尝试实现 application:didFailToRegisterForRemoteNotificationsWithError 了解更多信息
  • 我正在通过 firebase 控制台(通知)发送消息,并且我添加了 googleService-Info.plist。 didFailtoRegister 没有被调用。我正在获取设备令牌,但设备上没有通知
  • 是的,我的目标是单个设备,并将 FCM 注册令牌放在必填字段中。在 firebase 控制台中,消息状态已完成,但设备上没有推送通知。我已经检查了这两种状态,即在后台和前台都有应用程序。
  • 代码看起来正确。当您的应用程序处于活动状态时,您应该会看到 Connected to FCM,如果您重新安装应用程序,您应该会获得最新的令牌,但这并不重要,因为您可以从 firebase 控制台定位所有应用程序用户。我一定会仔细检查您的配置文件和证书是否设置正确:firebase.google.com/docs/cloud-messaging/ios/… 我无法真正发布答案,因为我也在设置它,我很幸运在职的。也没有太多可用的调试信息:(
  • 它正在发送消息“已连接到 FCM”,但没有通知,我遵循了相同的文档 :(

标签: ios objective-c


【解决方案1】:

如果您希望在应用程序处于后台时显示通知,您似乎需要将“优先级”设置为“高”:

Firebase IOS push notification doesn't work when app is closed

【讨论】:

    【解决方案2】:

    我对我的 iOS 应用做同样的事情。 FCM 和 GCM 不适用于 iOS。不管任何人说什么,它都不可能奏效。我花了 2 周时间在网上到处询问和寻找帖子。 iOS 将只接受 APNS 推送通知。免去您的麻烦,从应用程序开始。

    编辑: 这是 FCM 的最新存储库。试一试,看看结果如何。 https://github.com/firebase/quickstart-ios 它似乎与我在开发 iOS 版本时尝试的有所不同。 @Chris,这是你用来实现你的版本的代码分支吗?

    【讨论】:

    • 如果应用处于非活动状态,FCM 将委托给 APNS。我已成功从 firebase 控制台向我的 iphone 发送了推送通知(模拟器不支持推送通知)
    • 您是在使用 APNS 号码还是在使用 GCM/FCM 设备令牌。
    • 因为如果你只是使用 GCM,那么请制作一个完整的教程,一步一步地执行这个,因为我想知道怎么做
    • 连我也想知道。自 1 周以来,我一直在使用 GCM 和 FCM,但没有一个对我有用。请分享一些代码或一些有用的东西,以便我可以进一步处理。请尽快回复@chris。
    • @MNM 我还没有 100% 到达那里(我还不能从我自己的服务器触发 PN),但我已经很接近了。我可以在我的应用程序关闭和打开时从 firebase 控制台发送消息,在我的应用程序打开时从我的服务器发送消息。我只是按照官方指南:firebase.google.com/docs/cloud-messaging/ios/certs
    【解决方案3】:

    我也有同样的问题。我收到“已连接到 FCM”消息和令牌,似乎一切都完美集成,但无法收到任何通知。

    但是,我立即收到通知,但在没有任何代码更改和证书更改或删除之后,我无法收到任何进一步的通知。

    在这里查看我的代码,它是一个 cocos2d 应用程序。

    func didLoadFromCCB()
        {
        ...
        setupPushNotification()
    }
    
    func setupPushNotification () {
            let application = UIApplication.sharedApplication()
    
            // Register for remote notifications
            if #available(iOS 8.0, *) {
                let settings: UIUserNotificationSettings =
                UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
                application.registerUserNotificationSettings(settings)
                application.registerForRemoteNotifications()
            } else {
                // Fallback
                let types: UIRemoteNotificationType = [.Alert, .Badge, .Sound]
                application.registerForRemoteNotificationTypes(types)
            }
    
            FIRApp.configure()
    
            // Add observer for InstanceID token refresh callback.
            NSNotificationCenter.defaultCenter().addObserver(self, selector: "tokenRefreshNotification:",
                name: kFIRInstanceIDTokenRefreshNotification, object: nil)
    
            NSNotificationCenter.defaultCenter().addObserver(self, selector: "didBecomeActive:", name: UIApplicationDidBecomeActiveNotification, object: nil)
            NSNotificationCenter.defaultCenter().addObserver(self, selector: "didEnterBackground:", name: UIApplicationDidEnterBackgroundNotification, object: nil)
        }
    
    
    // [START refresh_token]
        func tokenRefreshNotification(notification: NSNotification) {
            let refreshedToken = FIRInstanceID.instanceID().token()!
            print("InstanceID token: \(refreshedToken)")
    
            // Connect to FCM since connection may have failed when attempted before having a token.
            connectToFcm()
        }
        // [END refresh_token]
    
        // [START connect_to_fcm]
        func connectToFcm() {
            FIRMessaging.messaging().connectWithCompletion { (error) in
                if (error != nil) {
                    print("Unable to connect with FCM. \(error)")
                } else {
                    print("Connected to FCM.")
                }
            }
        }
        // [END connect_to_fcm]
    
    func didBecomeActive(application:UIApplication) {
            NSLog("Did Become Active")
            connectToFcm()
        }
    
        func didEnterBackground(application: UIApplication) {
            NSLog("Did enter background")
            FIRMessaging.messaging().disconnect()
            NSLog("Disconnected from FCM.")
        }
    }
    

    我不知道我是如何得到那个只有一个正确的通知,然后它就扭转了局面。 :(

    让我知道如何解决这个问题。

    【讨论】:

    • 把这个放在另一个问题中,不要在这里
    【解决方案4】:

    尝试发送这个

    curl --header "Authorization: key={YOUR_API_KEY}" --header Content-Type:"application/json" https://fcm.googleapis.com/fcm/send -d "{\"to\":\"{YOUR_DEVICE_TOKEN}\",\"content_available\":true,\"priority\":\"high\",\"notification\":{\"title\":\"TEST\",\"sound\":\"default\",\"body\":\"IT WORKS!\",\"badge\":1}}"
    

    它对我有用。 (显然,先注册推送通知,然后打印出设备令牌)

    【讨论】:

      猜你喜欢
      • 2021-04-05
      • 2016-10-20
      • 1970-01-01
      • 2018-04-24
      • 2018-02-14
      • 2018-03-05
      • 1970-01-01
      • 2016-11-28
      • 2021-02-09
      相关资源
      最近更新 更多