2016-09-27 267 views
4

我很努力地顯示我從FCM通知控制檯發送給我的設備的推送通知。我可以看到設備正在接收的通知,因爲我可以看到我發送「test8」ios10,Swift 3和Firebase推送通知(FCM)

Connected to FCM. 
%@ [AnyHashable("notification"): { 
    body = test8; 
    e = 1; 
}, 

消息但是,如果我的應用是在我沒有得到通知顯示在前臺或後臺沒關係。

我在info.plist中添加了「所需的背景模式 - 應用程序下載內容以響應推送通知」。我的證書是正確的,我沒有問題生成一個令牌。我的應用程序正在接收通知,但沒有顯示它們。

import UIKit 
import UserNotifications 
import Firebase 
import FirebaseInstanceID 
import FirebaseMessaging 

@UIApplicationMain 
class AppDelegate: UIResponder, UIApplicationDelegate { 

    var window: UIWindow? 

    func application(application: UIApplication, 
        didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { 

     // [START register_for_notifications] 
     if #available(iOS 10.0, *) { 
      let authOptions : UNAuthorizationOptions = [.Alert, .Badge, .Sound] 
      UNUserNotificationCenter.currentNotificationCenter().requestAuthorizationWithOptions(
       authOptions, 
       completionHandler: {_,_ in }) 

      // For iOS 10 display notification (sent via APNS) 
      UNUserNotificationCenter.currentNotificationCenter().delegate = self 
      // 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() 
     } 

     application.registerForRemoteNotifications() 

     // [END register_for_notifications] 

     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) { 
     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() 
    } 
    // [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] 
} 

// [START ios_10_message_handling] 
@available(iOS 10, *) 
extension AppDelegate : UNUserNotificationCenterDelegate { 

    // Receive displayed notifications for iOS 10 devices. 
    func userNotificationCenter(center: UNUserNotificationCenter, 
           willPresentNotification notification: UNNotification, 
           withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void) { 
     let userInfo = notification.request.content.userInfo 
     // Print message ID. 
     print("Message ID: \(userInfo["gcm.message_id"]!)") 
     // Print full message. 
     print("%@", userInfo) 
    } 
} 

extension AppDelegate : FIRMessagingDelegate { 
    // Receive data message on iOS 10 devices. 
    func applicationReceivedRemoteMessage(remoteMessage: FIRMessagingRemoteMessage) { 
     print("%@", remoteMessage.appData) 
    } 
} 
// [END ios_10_message_handling] 

我一直在嘗試自己研究和解決這個問題,但我有問題。任何幫助或建議將不勝感激。

+0

難道ü解決問題烏爾,我不是在Xcode 8.1迅速2.3.since幾天我從服務器端嘗試我收到的,也當我送火力控制檯我收到,請您及時收到通知你能幫我嗎 。 –

回答

7

裏面方法didRegisterForRemoteNotificationsWithDeviceToken,添加以下代碼:

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) { 
    let tokenChars = UnsafePointer<CChar>(deviceToken.bytes) 
    var tokenString = "" 

    for i in 0..<deviceToken.length { 
     tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]]) 
    } 

    FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Unknown) 

    print("tokenString: \(tokenString)") 
} 

而且不要忘記啓用推送通知能力

+0

我添加了以下內容,因爲我使用的是swift語法,但它沒有解決我遇到的問題。我很欣賞這個建議。 FUNC應用(_應用:UIApplication的, didRegisterForRemoteNotificationsWithDeviceToken deviceToken:數據){ FIRInstanceID.instanceID()setAPNSToken(deviceToken,類型:FIRInstanceIDAPNSTokenType.sandbox)。 } –

+1

@Paul_D此行添加到您的Info.plist文件: FirebaseAppDelegateProxyEnabled和將布爾值設置爲NO –

+0

感謝您的幫助Gustavo。我仍在掙扎我收到以下錯誤... 無法獲取APNS令牌Error Domain = com.firebase.iid Code = 1001「(null)」。我收到的通知只是不顯示它們。我正在搜索谷歌,並盡我所能來解決這個問題。我知道我已經正確地將我的.p12認證上傳到了項目設置下的Firebase控制檯以及雲下消息傳遞。推送通知和(背景模式 - >遠程通知)都啓用。 –

3

你需要移動

application.registerForRemoteNotifications() 

它不應該是別人的內部。

// [START register_for_notifications] 
    if #available(iOS 10.0, *) { 
     let authOptions : UNAuthorizationOptions = [.Alert, .Badge, .Sound] 
     UNUserNotificationCenter.currentNotificationCenter().requestAuthorizationWithOptions(
      authOptions, 
      completionHandler: {_,_ in }) 

     // For iOS 10 display notification (sent via APNS) 
     UNUserNotificationCenter.currentNotificationCenter().delegate = self 
     // 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() 

See following commit in Firebase

+0

是的,這解決了我的問題!原始的源代碼必須更新! – Alexey

+0

謝謝,我也解決了我的問題。不過,你應該更新你的代碼swift 3. –

2

對我來說是缺少entitlements文件,所以在項目的Capabilities,你必須點擊修復問題。 Xcode會爲你設置文件。

enter image description here

+0

我認爲這將是大多數Xcode 8+用戶的修補程序!乾杯 – Josh