ios - Firebase 消息传递仅适用于前台

标签 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

当应用程序处于后台模式时,消息不来。当应用程序运行前台模式时,消息显示在 applicationReceivedRemoteMessage 函数中。当后台模式出现消息时,我需要运行一些代码。谁能给我在后台模式下获取通知的解决方案。

最佳答案

FIRMessaging connection won’t be allowed to live when in background it is prudent to close the connection.

请在此处找到相同的引用:disconnect()

FirebaseMessaging Framework Reference

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


一般情况下,Chat 应用程序与其他节点(设备)连接使用套接字连接,以在节点之间传输实时信息。 当应用进入后台时,套接字连接断开。

FirebaseMessaging 以相同的逻辑工作,因此不会在后台工作。

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

同时标记您的代码:当应用程序进入后台时,您将断开 FIRMessaging。您已经这样做了,因为 FIRMessaging 指南中也有同样的指示。

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

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

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

关于ios - Firebase 消息传递仅适用于前台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44844241/

相关文章:

ios - 使用 queryOrdered by date 对 Firebase 数据进行排序

android - 如何从 native 应用程序使用 Kurento 媒体服务器?

android - iphone 和 android 上的磁盘访问写入/更新数据的速度有多快

android - Firebase 测试实验室覆盖,Orchestrator 权限被拒绝

android - 适用于 Android 的 Firebase 触发器 Razorpay 集成

java - 如何在单击 Android 中的 Firestore 时删除 ListView 文档?

ios - AVCaptureVideoPreviewLayer 方向 - 需要横向

objective-c - NSURLConnection 异步上传文件?

iphone - 在表格 View 单元格上绘制一条线并将其移动到表格末尾时的 UITableview 可重用性问题

iphone - 如何在单击按钮时更改imageView中的图像