FCM通知在iOS上无法接收

3

我一直在尝试让我的iOS应用程序使用Firebase推送通知,已经有很长一段时间了。我尝试了互联网上能找到的一切方法,但遗憾的是没有成功。

非常感谢您的任何帮助。

我通过Firebase控制台发送通知。

这是我的代码:

#import "AppDelegate.h"

#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
@import UserNotifications;
#endif

@import Firebase;
@import FirebaseInstanceID;
@import FirebaseMessaging;

#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
@interface AppDelegate () <UNUserNotificationCenterDelegate, FIRMessagingDelegate>
@end
#endif

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.

    // [START configure_firebase]
    [FIRApp configure];
    // [END configure_firebase]

    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
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
        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];
#endif
    }

    [[UIApplication sharedApplication] registerForRemoteNotifications];

    // Add observer for InstanceID token refresh callback.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tokenRefreshNotification:)
                                                 name:kFIRInstanceIDTokenRefreshNotification object:nil];

    return YES;
}

// [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);

    NSLog(@"id = ---------- %@",[[[UIDevice currentDevice] identifierForVendor] UUIDString]);


    [[NSNotificationCenter defaultCenter] postNotificationName:@"fcmtoken" object:refreshedToken];


    // Connect to FCM since connection may have failed when attempted before having a token.
    [self connectToFcm];

    // TODO: If necessary send token to application server.
}
// [END refresh_token]

- (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(@"Message ID: %@", userInfo[@"gcm.message_id"]);

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

// [START ios_10_message_handling]
// Receive displayed notifications for iOS 10 devices.
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    // Print message ID.
    NSDictionary *userInfo = notification.request.content.userInfo;
    NSLog(@"Message ID: %@", userInfo[@"gcm.message_id"]);

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

// Receive data message on iOS 10 devices.
- (void)applicationReceivedRemoteMessage:(FIRMessagingRemoteMessage *)remoteMessage {
    // Print full message
    NSLog(@"message Recived = %@", [remoteMessage appData]);

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"ROFL"
                                                    message:@"Dee dee doo doo."
                                                   delegate:self
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:nil];
    [alert show];

}
#endif

// [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)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {

    NSLog(@"didRegisterForRemoteNotificationsWithDeviceToken");
    // for development
    [[FIRInstanceID instanceID] setAPNSToken:deviceToken type:FIRInstanceIDAPNSTokenTypeSandbox];

    // for production
    //     [[FIRInstanceID instanceID] setAPNSToken:deviceToken type:FIRInstanceIDAPNSTokenTypeProd];


}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

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

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.

    [self connectToFcm];
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end

在日志中,我能看到为我的设备生成的令牌,但是当我向应用程序发送通知时,当它处于后台状态时,应用程序无法接收通知。
但是当我启动我的应用程序时,它会调用applicationReceivedRemoteMessage:并显示警报。
请问可能的问题是什么?谢谢您的帮助!

在你的有效载荷中将优先级设置为高。 - Bhavin Bhadani
测试过了,但仍然没有帮助 :( - Krunal
发布你的有效载荷。 - Bhavin Bhadani
我正在使用 FCM 控制台发送通知。 - Krunal
4个回答

5
这种情况发生在我的项目中,是因为我正在使用在开发数据库中生成的相同的设备令牌...结果我需要在手机上删除并重新安装该应用程序,并注册通知以获取新的设备令牌和生成新的FCM注册ID...这样可以解决问题,我成功地收到了我的通知。
希望这可以帮助您。

2
当您的应用程序进入后台时,通知消息将由苹果APNS服务发送,所以我认为您的.cer有问题;苹果有两个.cer用于在编码/AppStore中推送通知,如果您的应用程序没有进入AppStore,尝试使用开发人员.cer来完成它。
我的英语不好,但可能对您有帮助!
====编辑==== 尝试这个吗? NSString *pushToken = [[[[deviceToken description]
                         stringByReplacingOccurrencesOfString:@"<" withString:@""]
                        stringByReplacingOccurrencesOfString:@">" withString:@""]
                       stringByReplacingOccurrencesOfString:@" " withString:@""];

我已经使用了开发者证书并将其添加到我的配置文件中。 - Krunal
已将 .p12 上传至 Firebase。 - Krunal
Xcode后台模式设置中是否打开了远程通知开关?或者尝试这个。 - darkThanBlack
哦,可能是因为你可以接收 Firebase 通知而导致 May 失效了。我崩溃了~ - darkThanBlack
我的完整经验是,如果iPhone在前台可以接收通知,但在后台无法接收,则可能是.cer问题,因为当应用程序在后台时,除了IDFA和APNS之外,没有人能找到该手机。希望对您有用... - darkThanBlack
显示剩余2条评论

0

通过打开推送通知来解决此问题。

您的项目 -> 能力 -> 打开推送通知


0

我通过在XCODE 8.1中启用推送通知功能来解决这个问题。

点击:

.xcodeproj -> 能力 -> 启用推送通知

然后我重新创建了配置文件。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接