使用obj c无法在设备中接收iOS Firebase推送通知

时间:2016-06-22 09:48:02

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

在我的应用程序中集成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];
}

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

  

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

2 个答案:

答案 0 :(得分: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()
}

答案 1 :(得分:0)

您是否在Firebase信息中心上正确设置了应用程序?

之前我遇到过此错误,因为FireMap控制台上的云消息设置并不太明显。

  1. 打开Firebase控制台。单击应用程序名称旁边的cog,然后继续&#34;项目设置&#34;。
  2. 选择云消息传递选项卡。您需要在此处添加iOS APNS证书才能成功发送推送消息(一个用于开发,一个用于生产)。
  3. 我收到此错误,因为我没有正确上传我的应用程序证书。

    <强>更新

    我遇到此错误的另一个原因是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证书并将其添加到您的配置文件中?