【问题标题】:objective C FCM how to get remote message when app in backgroundObjective C FCM如何在后台应用程序时获取远程消息
【发布时间】:2017-11-28 07:55:41
【问题描述】:

我的代码可以获取远程通知和远程消息,最后一个问题是应用程序在后台时无法获取远程消息(只需打开应用程序就可以了)

  • 当我在后台推送远程通知和应用程序时,似乎通知消息显示如预期,单击此通知然后将我带到我的应用程序。我不知道为什么远程消息没有这样的行为(我使用邮递员和“https://fcm.googleapis.com/fcm/send”发送远程消息)

    。请有人帮助我 这是我的代码

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
        // Register for remote notifications
        if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1) {
            // iOS 7.1 or earlier. Disable the deprecation warnings.
            UIRemoteNotificationType allNotificationTypes =
            (UIRemoteNotificationTypeSound |
             UIRemoteNotificationTypeAlert |
             UIRemoteNotificationTypeBadge);
            [application registerForRemoteNotificationTypes:allNotificationTypes];
    
        } else {
            // iOS 8 or later
            // [START register_for_notifications]
            if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_9_x_Max) {
                UIUserNotificationType allNotificationTypes =
                (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
                UIUserNotificationSettings *settings =
                [UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
                [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
            } else {
                // iOS 10 or later
      UNAuthorizationOptions authOptions =
                UNAuthorizationOptionAlert
                | UNAuthorizationOptionSound
                | UNAuthorizationOptionBadge;
                [[UNUserNotificationCenter currentNotificationCenter]
                 requestAuthorizationWithOptions:authOptions
                 completionHandler:^(BOOL granted, NSError * _Nullable error) {
                 }
                 ];
    
                // For iOS 10 display notification (sent via APNS)
                [[UNUserNotificationCenter currentNotificationCenter] setDelegate:self];
                // For iOS 10 data message (sent via FCM)
                [[FIRMessaging messaging] setRemoteMessageDelegate:self];
            }
    
            [[UIApplication sharedApplication] registerForRemoteNotifications];
            // [END register_for_notifications]
        }
    
        // [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 {
        // 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(@"didReceiveRemoteNotification1 ID: %@", userInfo[@"gcm.message_id"]);
    
        // Print full message.
        NSLog(@"didReceiveRemoteNotification1 %@", userInfo);
    }
    
    - (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(@"didReceiveRemoteNotification2 ID: %@", userInfo[@"gcm.message_id"]);
    
        // Print full message.
        NSLog(@"didReceiveRemoteNotification2 %@", userInfo);
    }
    - (void)userNotificationCenter:(UNUserNotificationCenter *)center
           willPresentNotification:(UNNotification *)notification
             withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
        // Print message ID.
        NSDictionary *userInfo = notification.request.content.userInfo;
        NSLog(@"willPresentNotification: %@", userInfo[@"gcm.message_id"]);
    
        // Print full message.
        NSLog(@"willPresentNotification %@", userInfo);
    }
    
    - (void)userNotificationCenter:(UNUserNotificationCenter *)center
    didReceiveNotificationResponse:(UNNotificationResponse *)response
             withCompletionHandler:(void (^)())completionHandler {
        NSDictionary *userInfo = response.notification.request.content.userInfo;
        NSLog(@"didReceiveNotificationResponse: %@", userInfo);
    }
    
    - (void)applicationReceivedRemoteMessage:(FIRMessagingRemoteMessage *)remoteMessage {
        NSLog(@"%@", [remoteMessage appData]);
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:[NSString stringWithFormat:@"%@", [remoteMessage appData]] delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Ok", nil];
        [alert show];
    }
    - (void)tokenRefreshNotification:(NSNotification *)notification {
    
        NSString *refreshedToken = [[FIRInstanceID instanceID] token];
        NSLog(@"InstanceID token: %@", refreshedToken);
        [self connectToFcm];
    }
    - (void)connectToFcm {
        [[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);
        [[FIRMessaging messaging] setAPNSToken:deviceToken];
    }
    
    - (void)applicationDidBecomeActive:(UIApplication *)application {
        [self connectToFcm];
    }
    
    - (void)applicationDidEnterBackground:(UIApplication *)application {
        [[FIRMessaging messaging] disconnect];
        NSLog(@"Disconnected from FCM");
    }
    

【问题讨论】:

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


    【解决方案1】:

    对于面临同样问题的其他人。

    经过大量搜索,我终于找到了解决方案,非常简单,您需要按照 Firebase 应用程序消息的内容,使其能够被推送通知服务读取。你可以看到here 和here

    这是让它在后台模式下显示给设备的示例:)

    {
      "condition": "'condition1' in topics && 'condition2' in topics",
      "notification": {
          "category": "notification_category",
          "title_loc_key": "notification_title",
          "body_loc_key": "notification_body",
          "badge": 1
      },
      "data": {
        "data_type": "notification_data_type",
        "data_id": "111111",
        "data_detail": "FOO",
        "data_detail_body": "BAR"
      }
    }
    

    现在一切都像预期的那样工作,那么第二个工作就是按照你想要的方式修改消息内容:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-18
      • 1970-01-01
      • 1970-01-01
      • 2017-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多