2016-08-07 7 views
1

Я не могу получить одно push-уведомление, отправленное на мое устройство. Я установил демонстрационное приложение с их демо-делегатом приложения, подписал его с профилем подготовки, с помощью приложение с поддержкой push-уведомлений и загрузило мой .p12 в панель администратора firebase, но независимо от того, что я пытаюсь (убираю все, и т. д.), я не могу отправить push-сообщение через консоль firebase. Что мне здесь не хватает?Firebase & Push Notifications/Cloud Messaging

Edit: я пытаюсь отправить весь сегмент, а также к одному устройству (с идентификатором, приведены в консоли)

import UIKit 
import Firebase 
import FirebaseInstanceID 
import FirebaseMessaging 

@UIApplicationMain 
class AppDelegate: UIResponder, UIApplicationDelegate { 

    var window: UIWindow? 


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { 
     // Register for remote notifications 
     if #available(iOS 8.0, *) { 
      // [START register_for_notifications] 
      let settings: UIUserNotificationSettings = 
       UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil) 
      application.registerUserNotificationSettings(settings) 
      application.registerForRemoteNotifications() 
      // [END register_for_notifications] 
     } else { 
      // Fallback 
      let types: UIRemoteNotificationType = [.Alert, .Badge, .Sound] 
      application.registerForRemoteNotificationTypes(types) 
     } 

     FIRApp.configure() 

     // Add observer for InstanceID token refresh callback. 
     NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.tokenRefreshNotification), 
                 name: kFIRInstanceIDTokenRefreshNotification, object: nil) 

     return true 
    } 

    // [START receive_message] 
    func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], 
        fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) { 
     // 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. 
     print("Message ID: \(userInfo["gcm.message_id"]!)") 

     // Print full message. 
     print("%@", userInfo) 
    } 
    // [END receive_message] 

    // [START refresh_token] 
    func tokenRefreshNotification(notification: NSNotification) { 
     let refreshedToken = FIRInstanceID.instanceID().token()! 
     print("InstanceID token: \(refreshedToken)") 

     // Connect to FCM since connection may have failed when attempted before having a token. 
     connectToFcm() 
    } 
    // [END refresh_token] 

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

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

    // [START disconnect_from_fcm] 
    func applicationDidEnterBackground(application: UIApplication) { 
     FIRMessaging.messaging().disconnect() 
     print("Disconnected from FCM.") 
    } 
    // [END disconnect_from_fcm] 
} 
+0

Просто убедитесь, что вы устанавливаете этот код на устройство или используете симулятор? Также полезно размещать журналы. У меня есть приложение с рабочим APN через Firebase. Как быстрый тест, можете ли вы подписаться на любую тему после подключения к «FIRMessaging»? Например: 'FIRMessaging.messaging(). SubscribeToTopic ("/topics/issues ")' – Mazyod

+0

Спасибо за ваш комментарий, но я действительно забыл didRegisterRemoteNotification. О, я такой слепой. –

ответ

3

Я не вижу, что вы звоните setAPNSToken, возможно, это то, что вам не хватает?

// AppDelegate.m 
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken 
{ 
    [firebaseManager didRegisterRemoteNotifications:deviceToken]; 
} 

// FirebaseManager.swift 
func didRegisterRemoteNotifications(deviceToken: NSData) { 

    let type: FIRInstanceIDAPNSTokenType 
    #if DEBUG 
     type = .Sandbox 
    #else 
     type = .Prod 
    #endif 

    FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: type) 
} 
+0

Спасибо, много! Я мог бы поклясться, что у меня это было, но этого не было. Какой-то раздражающий, поскольку я делал это на docs @ firebase.google.com, но они все равно сосут. Я предпочел старые документы, не относящиеся к google-дизайну firebase <3.0 больше :) –

+1

@ LucèBrùlè да, на самом деле .. Документация Firebase legacy была шедевром. Кроме того, я ответил на множество тривиальных вопросов о firebase здесь на SO недавно из-за их плохой новой документации. – Mazyod

Смежные вопросы