2016-12-15 74 views
8

我知道你以前偶然發現過這個問題;事實上有好幾次。但是我遵循每個提供給我的建議here,here,甚至hereFCM + Swift 3 - 沒有出現的通知

(寫在夫特3上的Xcode 8.1運行)

是的,在我的能力推送通知上。甚至我的背景模式的遠程功能是 - 我已經嘗試切換的FirebaseAppDelegateProxy開和關,檢驗證書(爲什麼,是的,它是指向正確的應用程序包),移動

application.registerForRemoteNotifications() 

哭了,消耗了大量的糖,向上帝祈禱,然後還有什麼其他相關的神靈我能想到,而且還沒有。

它可能只是第二組眼睛的尖叫需要,但任何想法?

import UIKit 
import UserNotifications 

import Firebase 
import FirebaseMessaging 


@UIApplicationMain 
class AppDelegate: UIResponder, UIApplicationDelegate { 

    var window: UIWindow? 
    let gcmMessageIDKey = "gcm.message_id" 


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { 
     FIRApp.configure() 
     // Override point for customization after application launch. 

     // Override point for customization after application launch. 
     // [START register_for_notifications] 
     if #available(iOS 10.0, *) { 
      let authOptions : UNAuthorizationOptions = [.alert, .badge, .sound] 
      UNUserNotificationCenter.current().requestAuthorization(
       options: authOptions, 
       completionHandler: {_,_ in }) 

      // For iOS 10 display notification (sent via APNS) 
      UNUserNotificationCenter.current().delegate = self 
      // For iOS 10 data message (sent via FCM) 
      FIRMessaging.messaging().remoteMessageDelegate = self 

     } else { 
      let settings: UIUserNotificationSettings = 
       UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil) 
      application.registerUserNotificationSettings(settings) 
     } 

     application.registerForRemoteNotifications() 

     // Add observer for InstanceID token refresh callback. 
     NotificationCenter.default.addObserver(self, 
                 selector: #selector(self.tokenRefreshNotification), 
                 name: NSNotification.Name.firInstanceIDTokenRefresh, 
                 object: nil) 

     return true 
    } 

    func tokenRefreshNotification(_ notification: Notification) { 
     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() 
    } 

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

    func applicationWillResignActive(_ application: UIApplication) { 
     // 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 invalidate graphics rendering callbacks. Games should use this method to pause the game. 
    } 

    func applicationDidEnterBackground(_ application: UIApplication) { 
     // 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. 
    } 

    func applicationWillEnterForeground(_ application: UIApplication) { 
     // 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. 
    } 

    func applicationDidBecomeActive(_ application: UIApplication) { 
     // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. 
    } 

    func applicationWillTerminate(_ application: UIApplication) { 
     // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. 
    } 


    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) { 
     // 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. 
     if let messageID = userInfo[gcmMessageIDKey] { 
      print("Message ID: \(messageID)") 
     } 

     // Print full message. 
     print(userInfo) 
    } 

    private func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) { 
//  let tokenChars = deviceToken.bytes 
     var tokenString = "" 

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

     FIRInstanceID.instanceID().setAPNSToken(deviceToken as Data, type: FIRInstanceIDAPNSTokenType.unknown) 

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

而且這裏的擴展...

import Foundation 
import UserNotifications 
import FirebaseMessaging 

@available(iOS 10, *) 
extension AppDelegate : UNUserNotificationCenterDelegate { 

    // Receive displayed notifications for iOS 10 devices. 

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (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) 
    } 
} 

令牌登錄到控制檯,FCM連接,雲端通訊抓住了我的證書......唯一可能的暗示我可能是Firebase控制檯不會將發送消息的一臺設備計爲「已發送」。

enter image description here 但控制檯看起來不錯。

2016-12-15 00:07:05.344 voltuser[4199:2008900] WARNING: Firebase Analytics App Delegate Proxy is disabled. To log deep link campaigns manually, call the methods in FIRAnalytics+AppDelegate.h. 
2016-12-15 00:07:05.349 voltuser[4199:2008900] Firebase automatic screen reporting is enabled. Call +[FIRAnalytics setScreenName:setScreenClass:] to set the screen name or override the default screen class name. To disable automatic screen reporting, set the flag FirebaseAutomaticScreenReportingEnabled to NO in the Info.plist 
2016-12-15 00:07:05.447 voltuser[4199] <Debug> [Firebase/Core][I-COR000001] Configuring the default app. 
2016-12-15 00:07:05.514: <FIRInstanceID/WARNING> Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001 "(null)" 
2016-12-15 00:07:05.520: <FIRMessaging/INFO> FIRMessaging library version 1.2.0 
2016-12-15 00:07:05.549 voltuser[4199:] <FIRAnalytics/INFO> Firebase Analytics v.3600000 started 
2016-12-15 00:07:05.549 voltuser[4199:] <FIRAnalytics/INFO> To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled (see this) 
2016-12-15 00:07:05.605 voltuser[4199] <Debug> [Firebase/Core][I-COR000018] Already sending logs. 
2016-12-15 00:07:05.679 voltuser[4199] <Debug> [Firebase/Core][I-COR000019] Clearcut post completed. 
2016-12-15 00:07:05.782 voltuser[4199] <Debug> [Firebase/Core][I-COR000019] Clearcut post completed. 
2016-12-15 00:07:05.824 voltuser[4199:] <FIRAnalytics/WARNING> The AdSupport Framework is not currently linked. Some features will not function properly. Learn more at here 
2016-12-15 00:07:07.286 voltuser[4199:] <FIRAnalytics/INFO> Firebase Analytics enabled 
InstanceID token: c_4iSvTQcHw:APA91bGjKnPoH9LysKl9CQxCJRJsfqwXBSUFAmgRp-KEWKjWqe2j4nt6Y5gx8us41rB6eLnRCOwRntnbr_N1fh_swz8j-GvvChSsV3gvG8dufVFLpagdtOxrxPSgLubQrfw-JqkA-4wV 
Connected to FCM. 
And the snapshot says Snap (mx7zr3y6XpSGZ4uB4PhZ8QRHIvt2) <null> 
[AnyHashable("notification"): { 
    body = "THIS IS SO PAINFUL"; 
    e = 1; 
    title = "WHY WONT YOU WORK"; 
}, AnyHashable("from"): 99570566728, AnyHashable("collapse_key"): com.mishastone.voltuser] 

...但消息記錄在我的控制檯很好。事實上,根本沒有出錯的錯誤!

嘆息

我的手機是沒有得到的前景,背景或任何形式的從應用程序通知 - 沒有什麼。壓縮。小人物。納達。只是我心碎的聲音。

我的iPhone當前位於9.3.5。如果這有助於任何。

任何幫助將不勝感激 - 或替代推送通知系統的建議...

+0

您是從Firebase Console還是從App Server發送通知?如果從App Server中,您可以添加示例負載嗎? –

+0

從Firebase控制檯。 –

+0

有沒有這個運氣?我目前也在同一條船上 – CharlieNorris

回答

10

想通了。 p.s.即時通訊使用的斯威夫特3語法,你缺少你willPresent方法

completionHandler 與通知的演示選項來執行該塊completionhandler。在執行此方法期間,始終在某個時刻執行此塊。

https://developer.apple.com/reference/usernotifications/unusernotificationcenterdelegate/1649518-usernotificationcenter

func userNotificationCenter(_ center: UNUserNotificationCenter, 
          willPresent notification: UNNotification, 
          withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { 
    let userInfo = notification.request.content.userInfo as! [String: Any] 



    completionHandler([.alert, .badge, .sound]) 

} 
+0

啊,所以就是這樣。我最終通過一遍又一遍地複製和粘貼示例代碼來修復我的錯誤。感謝您指出它的具體細節! –

+0

這是正確的嗎? OP說:「我的iPhone目前在9.3.5上」,但是這個功能(和你鏈接的文檔)說它是SDK 10.0+ – tospig

+0

你是救星bro!哇,真的非常感謝 – ken

0

如果你確信你的代碼是完美的,但你仍是無法接收FCM通知,請更新從火力地堡控制檯P12證書。您必須僅從Push證書導出安全密鑰並將其上載。您將開始接收通知。