FCM通知在iOS应用中无法正常工作

6
I am integrating FCM notification and cloud messaging in my app. I have followed the exact steps mentioned in Firebase documentation. I even tried using the sample code provided by FCM, but I encountered some warnings as follows: Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001 "The operation couldn’t be completed." FIRMessaging registration is not ready with auth credentials.
Here is the code I wrote in 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 以获取更多信息。 - Chris
我正在通过Firebase控制台发送消息(通知),并已添加googleService-Info.plist。但是didFailtoRegister没有被调用。我可以获取设备令牌,但设备上没有通知。 - ios
并且,我正在针对单个设备,并将FCM注册令牌放入必需的字段中。在Firebase控制台中,消息的状态为已完成,但设备上没有推送通知。我已经检查了应用程序在后台和前台两种状态下的情况。 - ios
代码看起来正确。当您的应用程序处于活动状态时,您应该会看到连接到 FCM,并且如果您重新安装您的应用程序,您应该会获得最新的令牌,尽管这并不重要,因为您可以从 Firebase 控制台针对所有应用程序用户进行定位。我建议您仔细检查您的配置文件设置以及证书:https://firebase.google.com/docs/cloud-messaging/ios/certs#create_an_app_id我无法提供答案,因为我也在设置此项功能,而且我很幸运它能正常工作。也没有太多调试信息可用 :( - Chris
Chris,我有一个问题,你在用付费版吗?我正在使用免费版(Spark)。 - ios
显示剩余2条评论
4个回答

1

0

我在我的iOS应用程序中也做了同样的事情。FCM和GCM在iOS上不起作用。无论别人说什么,都没有机会让它工作。我花了两个星期到网上各处询问和查找帖子。iOS只接受APNS推送通知。节省自己的头疼,从应用程序开始。

编辑: 这是FCM的最新存储库。试试看有什么结果。 https://github.com/firebase/quickstart-ios 它似乎与我在制作iOS版本时尝试的那个有点不同。 @Chris,这是您用来实现您的版本的代码分支吗?


如果应用程序处于非活动状态,则 FCM 代表将委托给 APNS。我已成功从 Firebase 控制台向我的 iPhone 发送推送通知(模拟器不支持推送通知)。 - Chris
如果您只是使用GCM,那么请提供一个完整的教程,包括逐步过程,以便我了解如何操作。 - MNM
@Chris,是的,这就是你使用APNS发送PN的方式。我已经完成了这个过程。但我仍然无法使用它来发送GCM。谷歌提供的代码只提供GCM的令牌,而不是APNS的令牌。而GCM将不会使用APNS令牌来发送PN。而iOS只接受APNS令牌,其他的都不行。 - MNM
@Chris 是的,那应该是它的工作方式。但我在发送 pn 时遇到了各种问题。你能够成功发送它很有趣。你在 Xcode 中的构建设置是怎样的?并且你能告诉我们你正在使用哪个版本的 Xcode 和 iOS 吗? - MNM
@Chris,我正在研究FCM,想知道在注册该服务时,你会得到什么样的令牌格式。比如说,它是十六进制代码,像这样:13596673c79ed4d340c208bd994bc954ee1bac64c90701e6088122be17f6ebr5,还是GCM类型的代码,像这样:fz-Z4ZLSgoU:APA91bFQ3Owt9as73GAZKJy0m5TmAa3OncaOcBoYSDSXdqR0nGsoOWHyky_N1IU14lD73QEPziqsbpu6otmLwzPGHOAukuN_Bw8xuY7ISWcn6eCuMgCkqNuK5I2fF7Kshowjox8RG-7S? - MNM
显示剩余8条评论

0
我也遇到了同样的问题。我收到了“已连接到 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.")
    }
}

我不知道怎么会出现只有一条正确的通知,然后就变成了错误的了 :(

请告诉我如何解决这个问题。


请将此内容放在另一个问题中,而不是在这里。 - MNM

0

尝试发送这个

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}}"

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接