2017-08-05 128 views
0

我已经在FCM上上传了开发和生产证书,在功能中启用了推送通知,在我的项目中放置了GoogleService-Info.plist。 我试着制作另一个Google帐户,然后重试所有的程序,但没有为我工作。未收到Firebase对iOS应用的推送通知应用

我试图发送通知到单个设备令牌,但它被拒绝表示“无效登记token.check令牌格式”

下面是我尝试的代码。

- (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]; 
} 
+0

令牌哪些您使用的是?你在使用设备令牌吗? –

+0

尝试使用选择的应用发送。而不是单个设备。或确保您已在项目设置选项卡中上传正确的.p12文件。 – KKRocks

+0

如果你最近添加.p12,那么你需要重新下载谷歌配置文件,并用旧的替换。 – KKRocks

回答

0

看起来你正在使用设备令牌从火力控制台发送推送通知。如果这是真的,你不应该使用设备令牌。相反,Firebase会为您提供FCMRegistration令牌。尝试使用该令牌向该特定设备发送通知。

摘自我的文章。

要发送推送通知到特定设备,我们需要 设备令牌。当您在设备上运行应用程序(不在 模拟器上)并且如果设置正确,控制台将打印 设备令牌和FCM注册令牌。两者都相似,但不是 相同。当我们通过一些第三方服务或我们自己的服务器发送推送通知 时,我们使用设备令牌。如果我们通过 发送推送通知,我们使用FCM 注册令牌。所以在我们的例子中,我们将FCM注册令牌 印在控制台上。

enter image description here 下面是我对How to send push notifications using firebase

产生额外的信息文章:在情况下,如果你想尝试检查是否配置了推送通知代码正确或不使用第三方库像Pusher 但这实时使用设备令牌在推进器中检查。

+0

我试过这个,FCM拒绝它显示它是无效的 –

0

可能是这是你面临的问题。

您需要为您的APNS上传正确的.p12文件。

你需要简单地转到项目设置然后在云端通讯

在这里,你需要添加.p12文件。

enter image description here

上传后,您需要重新下载配置文件和旧的替换。

解决方案2

我已经上传SWIFT代码,如果你能理解然后将其转换到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) 
    } 

能力标签,它应该像也

enter image description here

+0

我也是这样做的。 :( –

+0

@Shikha Sharma我可以添加我的swift代码,在我的项目中工作正常 – KKRocks

+0

是的,它会帮助我,虽然我需要objective-s,但它是好的图集我会得到一些帮助 –

0

使用此代码:

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