FCM通知在ios中不起作用

时间:2016-05-31 06:28:00

标签: ios objective-c

我正在我的app.i中集成FCM通知和云消息,其遵循与firebase doc中提到的完全相同的步骤。即使我尝试过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]

希望尽快得到答复。 提前谢谢!

4 个答案:

答案 0 :(得分:1)

您似乎需要拥有&#34;优先级&#34;设置为&#34;高&#34;如果您希望在应用程序处于后台时显示通知:

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

答案 1 :(得分:0)

我在iOS应用程序中做了同样的事情。 FCM和GCM不适用于iOS。不管别人怎么说,它都没有机会发挥作用。我花了两个星期的时间在网上到处寻找和寻找帖子。 iOS只接受APNS推送通知。让自己远离头痛并从应用程序开始。

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

答案 2 :(得分: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.")
    }
}

我不知道如何只有一个正确的通知,然后它变成了表格。 :(

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

答案 3 :(得分: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}}"

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