objective C FCM如何在后台应用程序时获取远程消息

时间:2017-11-28 07:55:42

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

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

  • 当我在后台推送远程通知和应用程序时,它看起来像是期待的通知消息显示,点击此通知然后它将我带到我的应用程序。我不知道为什么远程消息没有这样的行为(我使用postman和“https://fcm.googleapis.com/fcm/send”来发送远程消息)

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

    - (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");
    }
    

1 个答案:

答案 0 :(得分:0)

对于遇到同样问题的其他人。

经过大量搜索,我找到了解决方案,非常简单,你需要按照firebase app消息的内容使其通过推送通知服务可读。你可以看到herehere

这是在背景模式下向设备显示的示例:)

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

现在一切都像期待的那样,然后第二个工作就是修改消息内容,就像你想要的那样:)