【问题标题】:iOS Firebase Push Notifications not receive in device using obj c使用 obj c 在设备中未收到 iOS Firebase 推送通知
【发布时间】:2016-10-24 04:18:35
【问题描述】:

在我的应用程序中集成 Firebase 云消息传递。成功安装 pod 并获取所有框架。我想为我的设备获取 refreshedToken 并在我的设备中发送和接收通知,并希望跟踪我的应用中的所有按钮点击。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1) {
        // iOS 7.1 or earlier
        UIRemoteNotificationType allNotificationTypes =
        (UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge);
        [application registerForRemoteNotificationTypes:allNotificationTypes];
    } else {
        // iOS 8 or later
        // [END_EXCLUDE]
        UIUserNotificationType allNotificationTypes =
        (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
        UIUserNotificationSettings *settings =
        [UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    }

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


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

    // Pring full message.
    NSLog(@"%@", userInfo);
}

- (void)connectToFcm {
    [[FIRMessaging messaging] connectWithCompletion:^(NSError * _Nullable error) {
        if (error != nil) {
            NSLog(@"Unable to connect to FCM. %@", error);
        } else {
            NSLog(@"Connected to FCM.");
        }
    }];
}



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

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

    // TODO: If necessary send token to appliation server.
}

- (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 throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    [[FIRMessaging messaging] disconnect];

    // 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.
}

- (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
{
    [self connectToFcm];
}

我在应用委托中使用此代码。在我的代码中得到了这些警告。我该如何解决这个问题。新的开发帮助我。

警告:Firebase Analytics 应用程序委托代理已禁用。要手动记录深度链接活动,请调用 FIRAnalytics+AppDelegate.h 中的方法。 FCMAPP[496:56073] 配置默认应用程序。 无法获取 APNS 令牌错误域 = com.firebase.iid 代码 = 1001“(空)” FIRMessaging 库版本 1.1.0 Firebase Analytics v.3200000 已启动 要启用调试日志记录,请设置以下应用程序参数:-FIRAnalyticsDebugEnabled FIRMessaging 注册尚未准备好使用身份验证凭据 FCMAPP[496:56073] 无法连接到 FCM。错误 Domain=com.google.fcm Code=501 "(null)"

【问题讨论】:

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


    【解决方案1】:

    使用以下 Swift 代码。

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

    【讨论】:

      【解决方案2】:

      您是否在 Firebase 仪表板上正确设置了应用程序?

      我之前遇到过此错误,因为 Cloud Messaging 设置在 Firebase 控制台上不太明显。

      1. 打开 Firebase 控制台。单击应用程序名称旁边的齿轮,然后继续“项目设置”。
      2. 选择云消息选项卡。您需要在此处添加您的 iOS APNS 证书才能成功发送推送消息(一个用于开发,一个用于生产)。

      我收到此错误是因为我没有正确上传我的应用证书。

      更新:

      我遇到此错误的另一个原因是 Firebase SDK 有时无法从苹果本身获取 APNS 令牌。为了解决这个问题,我手动获取了令牌:

      首先注册远程通知:

      - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
      
      ...
      
        // Register for remote notifications.
      [[UIApplication sharedApplication] registerForRemoteNotifications];
      
      }
      

      当 APNS 令牌返回时,在 Firebase 实例上手动设置它:

      - (void)application:(UIApplication *)app
      didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)devToken {
      
      NSLog(@"Registered for notification device token: %@", devToken);
      
      [[FIRInstanceID instanceID] setAPNSToken:devToken type:FIRInstanceIDAPNSTokenTypeUnknown];
      
      [self connectToFcm];
      
      const void *devTokenBytes = [devToken bytes];
      
      }
      

      然后应该能够成功连接到 Firebase 云消息传递:

      - (void)connectToFcm {
      
      NSLog(@"Connecting to FCM...");
      
      [[FIRMessaging messaging] connectWithCompletion:^(NSError * _Nullable error) {
          if (error != nil) {
              NSLog(@"Unable to connect to FCM. %@", error);
          } else {
              NSLog(@"Connected to FCM.");
          }
      }];
      }
      

      如果您无法通过这种方式获取 APNS 令牌,则说明您在 Apple 会员中心设置的推送通知有问题。您是否已生成开发者/发布 APNS 证书并将其添加到您的配置文件中?

      【讨论】:

      • 我从 firebase 控制台发送通知,它应该成功显示在我的 Xcode 控制台中。但我没有在我的设备中收到推送通知消息。如何解决 tis 问题。
      • 我已经用更好的解决方案更新了我的答案。我记得我也遇到过这个问题,因为 Firebox 无法从苹果本身获取 APNS 令牌。
      • 对不起,我无法清楚地告诉你.. 想要做什么。请在我上面的代码中进行更改。我仍然无法在我的设备中收到推送通知。我做错了什么,知道帮助我。
      • 只需将[[UIApplication sharedApplication] registerForRemoteNotifications]; 添加到didFinishLaunchingWithOptions 方法的底部即可。然后检查您是否在didRegisterForRemoteNotificationsWithDeviceToken 中收到令牌。
      • 是的,我像这样设备令牌 我复制了这个设备令牌放在 firebase 通知页面。选择单个设备并将其粘贴,键入味精并发送。在控制台而不是设备中收到消息。如何解决这个问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-12
      • 1970-01-01
      • 2016-01-03
      • 2018-09-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多