简体   繁体   English

没有收到从Firebase到iOS App的推送通知

[英]Not receiving push notifications from Firebase to iOS App

I've uploaded development and production certificates on FCM, Enabled push notification in Capabilities, Placed GoogleService-Info.plist in my project. 我已经在FCM上上传了开发和生产证书,在功能中已启用推送通知,在项目中放置了GoogleService-Info.plist。 I've tried making another Google account and trying again all the procedure but nothing worked for me. 我尝试过建立另一个Google帐户,然后再次尝试所有过程,但对我来说没有任何用。

I tried sending notification to single device token, but it gets rejected showing "Invalid registration token.check token format" 我尝试将通知发送到单个设备令牌,但是拒绝显示“无效的注册令牌。检查令牌格式”

Below is the code I tried. 下面是我尝试的代码。

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

    NSError *configureError;
[[GGLContext sharedInstance] configureWithError:&configureError];
NSAssert(!configureError, @"Error configuring Google services: %@", configureError);



GAI *gai = [GAI sharedInstance];
gai.trackUncaughtExceptions = YES;
gai.logger.logLevel = kGAILogLevelVerbose;

if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1) {

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
    UIRemoteNotificationType allNotificationTypes =
    (UIRemoteNotificationTypeSound |
     UIRemoteNotificationTypeAlert |
     UIRemoteNotificationTypeBadge);
    [application registerForRemoteNotificationTypes:allNotificationTypes];
#pragma clang diagnostic pop
} else {

    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 {

#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0

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


        [FIRMessaging messaging].remoteMessageDelegate = self;
#endif
    }

    [[UIApplication sharedApplication] registerForRemoteNotifications];
}


[FIRApp configure];

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


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

[[FIRMessaging messaging] disconnect];

}

- (void)applicationDidBecomeActive:(UIApplication *)application {
[self connectToFirebase];


 application.applicationIconBadgeNumber = 0;
}

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

}

#pragma mark -- Custom Firebase code


- (void)tokenRefreshCallback:(NSNotification *) notification{
NSString *refreshedToken = [[FIRInstanceID instanceID] token];

[self connectToFirebase];
}

-(void) connectToFirebase{

[[FIRMessaging messaging] connectWithCompletion:^(NSError * _Nullable error)
 {
     if ( error != nil)
     {

     }
     else
     {

     }
 }];
}
- (void)applicationWillResignActive:(UIApplication *)application {}


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


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

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
if (userInfo[kGCMMessageIDKey]) {

    NSLog(@"%@",userInfo);
}}


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

NSDictionary *userInfo = notification.request.content.userInfo;
if (userInfo[kGCMMessageIDKey]) {

}


completionHandler(UNNotificationPresentationOptionNone);
}

 - (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
     withCompletionHandler:(void (^)())completionHandler {
   NSDictionary *userInfo = response.notification.request.content.userInfo;
if (userInfo[kGCMMessageIDKey]) {

}

completionHandler();
  }

- (void)connectToFcm {

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

[[FIRMessaging messaging] disconnect];

[[FIRMessaging messaging] connectWithCompletion:^(NSError * _Nullable error) {
    if (error != nil) {

    } else {

    }
}];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
NSLog(@"PUSH ERROR: %@", error);
}

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

- (void)applicationReceivedRemoteMessage:(FIRMessagingRemoteMessage *)remoteMessage {

}

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

NSString *refreshedToken = [[FIRInstanceID instanceID] token];    
NSLog(@"%@",refreshedToken);

[self connectToFcm];

}

- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{

[application registerForRemoteNotifications];
}

Looks like you are using device token to send push notifications from firebase console. 似乎您正在使用设备令牌从Firebase控制台发送推送通知。 If that's true, you shouldn't use device token. 如果是这样,则不应使用设备令牌。 Instead, Firebase will give you FCMRegistration token. 相反,Firebase将为您提供FCMRegistration令牌。 Try to use that token to send a notification to that specific device. 尝试使用该令牌向该特定设备发送通知。

Excerpted from my article. 摘自我的文章。

To send a push notification to the particular device we need the device token. 要将推送通知发送到特定设备,我们需要设备令牌。 When you run the application on your device(Not on a simulator) and if your setup is correct, your console will print Device token and FCM registration token. 当您在设备上(而不是在模拟器上)运行应用程序时,如果设置正确,则控制台将打印设备令牌和FCM注册令牌。 Both are similar but not the same. 两者相似但不相同。 Device token we use when we are sending push notifications through some third party services or our own server. 通过某些第三方服务或我们自己的服务器发送推送通知时使用的设备令牌。 We use FCM registration token if we are sending push notifications through firebase console. 如果我们通过Firebase控制台发送推送通知,则使用FCM注册令牌。 So in our case, we take FCM registration token which is printed on the console. 因此,在我们的情况下,我们采用打印在控制台上的FCM注册令牌。

在此处输入图片说明 Below is my article on How to send push notifications using firebase 以下是我有关如何使用Firebase发送推送通知的文章

Additonal Info: In case, if you want to try checking whether your push notifications code configured correctly or not use third party library like Pusher But this time use device token in pusher to check. 附加信息:以防万一,如果您想尝试检查您的推送通知代码是否配置正确,请使用诸如Pusher之类的第三方库,但这一次使用pusher中的设备令牌进行检查。

Might be this is the issue you are faced. 可能这就是您面临的问题。

You need to upload correct .p12 file for Your APNS . 您需要为APNS上传正确的.p12文件。

You need to simply Goto Project Setting then under Cloud Messaging 您只需简单地转到项目设置,然后在云消息传递下

Here you need to add your .p12 file. 在这里,您需要添加.p12文件。

在此处输入图片说明

After uploading you need to redownload configuration file and replace with old one. 上传后,您需要重新下载配置文件并用旧的替换。

Solution 2 解决方案2

I have upload swift code if you can understand then convert it to objective-c because i don't have objective-c code. 如果您可以理解,我已经上传了快速代码,然后将其转换为Objective-C,因为我没有Objective-C代码。

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
      FirebaseApp.configure()
    if #available(iOS 10.0, *) {
      // For iOS 10 display notification (sent via APNS)
      UNUserNotificationCenter.current().delegate = self

      let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
      UNUserNotificationCenter.current().requestAuthorization(
        options: authOptions,
        completionHandler: {_, _ in })
    } else {
      let settings: UIUserNotificationSettings =
        UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
      application.registerUserNotificationSettings(settings)
    }
    application.registerForRemoteNotifications()

    return true
  }

func application(_ application: UIApplication,
                   didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    Messaging.messaging().apnsToken = deviceToken as Data
    var token: String = ""
    for i in 0..<deviceToken.count {
      token += String(format: "%02.2hhx", deviceToken[i] as CVarArg)
    }

    print(token)
  }

In capabilities tab, it should be like also 功能选项卡中,它也应该像

在此处输入图片说明

Use This Code: 使用此代码:

 func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
{
    if #available(iOS 10.0, *)
    {
        // For iOS 10 display notification (sent via APNS)
        UNUserNotificationCenter.currentNotificationCenter().delegate = self
        UNUserNotificationCenter.currentNotificationCenter().requestAuthorizationWithOptions([.Badge, .Sound, .Alert])          { (granted, error) in
                if granted
                {
                //self.registerCategory()
             }
         }
         // For iOS 10 data message (sent via FCM)
         FIRMessaging.messaging().remoteMessageDelegate = self
    }
    else
    {
        let settings: UIUserNotificationSettings =  UIUserNotificationSettings(forTypes: [.Alert,.Badge,.Sound], categories: nil)
        application.registerUserNotificationSettings(settings)
    }          
    application.registerForRemoteNotifications()        
    //Configuring Firebase
    FIRApp.configure()
    // Add observer for InstanceID token refresh callback.
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.tokenRefreshNotification), name: kFIRInstanceIDTokenRefreshNotification, object: nil)     
     return true
}

//Receive Remote Notification on Background
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void)
{
    FIRMessaging.messaging().appDidReceiveMessage(userInfo)
}

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData)
{
    FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Sandbox)
    FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Prod)
}

func tokenRefreshNotification(notification: NSNotification)
{
    if let refreshedToken = FIRInstanceID.instanceID().token()
    {
            print("InstanceID token: \(refreshedToken)")
    }
    // Connect to FCM since connection may have failed when attempted before having a token.
    connectToFcm()
}

func connectToFcm()
{
    FIRMessaging.messaging().connectWithCompletion { (error) in
            if (error != nil)
            {
                print("Unable to connect with FCM. \(error)")
            }
            else
            {
                print("Connected to FCM.")
            }
    }
}

func applicationDidBecomeActive(application: UIApplication)
{            
    connectToFcm()
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM