Firebase消息传递仅适用于前台

时间:2017-06-30 10:25:24

标签: ios objective-c firebase firebase-cloud-messaging

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    [UNUserNotificationCenter currentNotificationCenter].delegate = self;
    UNAuthorizationOptions authOptions =
    UNAuthorizationOptionAlert
    | UNAuthorizationOptionSound
    | UNAuthorizationOptionBadge;
    [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) {


    }];


    [FIRMessaging messaging].remoteMessageDelegate = self;

    [[UIApplication sharedApplication] registerForRemoteNotifications];

    [FIRApp configure];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tokenRefreshNotification:)
                                                 name:kFIRInstanceIDTokenRefreshNotification object:nil];


    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {

}

- (void)applicationDidEnterBackground:(UIApplication *)application {


   [[FIRMessaging messaging] disconnect];
   NSLog(@"Disconnected from FCM");
}

- (void)applicationWillEnterForeground:(UIApplication *)application {


}

- (void)applicationDidBecomeActive:(UIApplication *)application {


    [self connectToFcm];

}

- (void)applicationWillTerminate:(UIApplication *)application {

}




- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {



    // Print message ID.
    NSLog(@"message 1");
    if (userInfo[kGCMMessageIDKey]) {
        NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
    }

    // Print full message.
    NSLog(@"%@", userInfo);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {


    // Print message ID.
    NSLog(@"message 2");
    if (userInfo[kGCMMessageIDKey]) {
        NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
    }


    NSLog(@"%@", userInfo);

    completionHandler(UIBackgroundFetchResultNewData);
}



- (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {

    NSLog(@"message 3");
    NSDictionary *userInfo = notification.request.content.userInfo;
    if (userInfo[kGCMMessageIDKey]) {
        NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
    }


    NSLog(@"full data : %@", userInfo);

    completionHandler(UNNotificationPresentationOptionAlert);


}



- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
         withCompletionHandler:(void (^)())completionHandler {
    NSDictionary *userInfo = response.notification.request.content.userInfo;
    NSLog(@"message 1");
    if (userInfo[kGCMMessageIDKey]) {
        NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
    }

    // Print full message.
    NSLog(@"%@", userInfo);

    completionHandler();
}

- (void)applicationReceivedRemoteMessage:(FIRMessagingRemoteMessage *)remoteMessage {
    // Print full message
    NSLog(@"applicationReceivedRemoteMessage  : %@", remoteMessage.appData);

}


- (void)tokenRefreshNotification:(NSNotification *)notification {

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *refreshedToken = [[FIRInstanceID instanceID] token];
    NSLog(@"InstanceID token: %@", refreshedToken);

    if(!(refreshedToken== nil)){
        [defaults setValue:refreshedToken forKey:@"FcmToken"];
    }


    [self connectToFcm];


}

- (void)connectToFcm {

    if (![[FIRInstanceID instanceID] token]) {
        return;
    }


    [[FIRMessaging messaging] disconnect];

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

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"Unable to register for remote notifications: %@", error);
}


- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSLog(@"APNs token retrieved: %@", deviceToken); 
}

enter code here

当应用处于后台模式时,消息不会出现。当app正在运行前台模式时,messageReceivedRemoteMessage函数中会显示消息。当背景模式出现消息时,我需要运行一些代码。任何人都可以给我解决方案,让通知在后台模式下工作。

1 个答案:

答案 0 :(得分:1)

  

在后台进行FIRMessaging连接时不允许有效   谨慎地关闭连接。

请在此处查找相同的参考:disconnect()

FirebaseMessaging Framework Reference

关于聊天应用程序的简单逻辑:套接字连接

通常,聊天应用程序使用套接字连接与其他节点(设备)连接,以在节点之间传输实时信息。 当应用进入后台时,套接字连接断开连接。

FirebaseMessaging在相同的逻辑上工作,因此无法在后台工作。

要在后台模式下处理消息传输,请使用 PushNotification 的强大功能。

同时标记您的代码:当应用程序进入后台时,您正在断开FIRMessaging。而且您已经完成了这项工作,因为FIRMessaging指南中也指示了相同的内容。

- (void)applicationDidEnterBackground:(UIApplication *)application {

   [[FIRMessaging messaging] disconnect];
   NSLog(@"Disconnected from FCM");
}

作为您问题的替代解决方案:您可能已经分析过Whatapp或Facebook Messagner应用。当应用程序进入后台时,他们使用推送通知来提醒用户输入消息。你也应该这样做。

相关问题