2017-08-05 126 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() 
}