云消息处理终止应用程序

Cloud messaging handing terminate app

我有一个在 NSUserDefaults 中存储用户会话的应用程序。当应用程序被强制关闭时,在初始验证数据控制器用户会话是否存在,如果存在则发送到开始window如下:

override func viewWillAppear(animated: Bool) {

    self.view.hidden = true

    let defaults = NSUserDefaults.standardUserDefaults()
    if   defaults.stringForKey("user") != nil
    {

        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            let viewController:UIViewController = self.storyboard?.instantiateViewControllerWithIdentifier("vistaInicio") as! ViewControllerInicio
            self.presentViewController(viewController, animated: true, completion: nil)
        })


    }else
    {
    self.view.hidden = false

    }

}

直到今天,当我决定按照本教程更新 firebase 来实施推送通知时,这对我来说一直很顺利 在 iOS 上设置 Firebase 云消息传递客户端应用程序。当他杀死应用程序并再次输入时出现问题,给出以下错误代码:

 2016-05-19 16:05:27.647: <FIRInstanceID/WARNING> Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001 "(full)"
 2016-05-19 16:05:27.659: <FIRMessaging/INFO> FIRMessaging library version 1.1.0
 2016-05-19 16:05:27.831: <FIRMessaging/WARNING> FIRMessaging registration is not ready with auth credentials
Unable to connect with FCM. Optional(Error Domain=com.google.fcm Code=501 "(null)")

这是解决方案,

首先在 Firebase 控制台中上传必要的证书然后在您的应用中启用推送通知和后台模式 -> 远程通知

之后在 App Delegate 中使用下面的代码(我指定了棘手的行):

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    registerForPushNotifications(application)
    // Override point for customization after application launch.
    // Use Firebase library to configure APIs
    FIRApp.configure()
    return true
}

func registerForPushNotifications(application: UIApplication) {
    let notificationSettings = UIUserNotificationSettings(
        forTypes: [.Badge, .Sound, .Alert], categories: nil)
    application.registerUserNotificationSettings(notificationSettings)
}

func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
    if notificationSettings.types != .None {
        application.registerForRemoteNotifications()
    }
}

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

    //Tricky line
    FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Unknown)
    print("Device Token:", tokenString)
}

不要忘记在 AppDelegate 中:

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

    registerForPushNotifications(application)
    FIRApp.configure()

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

    // Override point for customization after application launch.
    return true
  }

func registerForPushNotifications(application: UIApplication) {
      let settings: UIUserNotificationSettings =
        UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
      application.registerUserNotificationSettings(settings)
      application.registerForRemoteNotifications()
  }


  func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
                   fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
    print("===== didReceiveRemoteNotification ===== %@", userInfo)
  }


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

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

请确保也在 Info.plist 中执行:FirebaseAppDelegateProxyEnabled = NO

我现在不知道,但我在 didReceiveRemoteNotification 中得到了 print(...),但没有得到弹出窗口。我从 Firebase -> Console -> Notification -> Single device 发送消息,并将我从 Xcode Console -> func tokenRefreshNotificaiton[= 获得的令牌复制到这里15=]

答案是正确的那些是步骤,但也请检查您的设备时间。因为如果你的时间和日期太晚,它就不会工作

在对整个集成进行三重检查后,对我来说问题是测试设备的日期提前一周更改了。 FCM SDK 可能会进行一些基于日期的检查。

这个错误在 Firebase 方面可能不太常见,因为我几乎花了一天时间寻找解决方案。希望这有帮助。