iOS Firebase推送通知:如何提供Firebase用户的设备令牌并发送通知 [英] iOS Firebase Push Notifications : How To Give Firebase User's Device Token And Send Notification

查看:1523
本文介绍了iOS Firebase推送通知:如何提供Firebase用户的设备令牌并发送通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近在Google I / O活动中,Google重新整理了Firebase,并添加了许多新功能,并且触及了其余的功能。我一直试图通过Firebase将iOS推送通知实现到我的应用程序的最基本的级别,所以我创建了一个非常简单的应用程序,除了接收远程推送通知之外什么也没做。在Firebase内部,我已经上传了我的证书,在Xcode中,我的配置文件已经添加到目标和项目中,并且在Firebase中我已经上传了正确的证书。下面是我的 AppDelegate.swift 文件中包含的代码,但是因为我的 ViewController.swift 是空的,所以我没有包括它。虽然没有崩溃或运行时错误,当我加载应用程序时,我接受通知。然后,我退出应用程序并关闭我的设备。在Firebase中,我将通知发送到正确的应用程序。几分钟后,Firebase表示通知已完成。但是,我从来没有收到设备上的通知。因此,最后,我需要一个解决方案来发送Firebase这个 deviceToken ,然后使用Firebase通知发送推送通知消息。任何帮助我的代码或一般将不胜感激,我希望这有助于未来的观众。谢谢!我的代码位于 AppDelegate.swift
$ b

  import UIKit 
导入Firebase
导入FirebaseMessaging

@UIApplicationMain $ b $ class AppDelegate:UIResponder,UIApplicationDelegate {

var window:UIWindow?

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

FIRApp.configure()

let notificationTypes:UIUserNotificationType = [UIUserNotificationType.Alert,UIUserNotificationType.Badge,UIUserNotificationType.Sound]

let notificationSettings = UIUserNotificationSettings(forTypes:notificationTypes,类别:nil)

application.registerForRemoteNotifications()
application.registerUserNotificationSettings(notificationSettings)

return true
}

func application(application:UIApplication,didRegisterForRemoteNotificationsWithDeviceToken deviceToken:NSData){

print(Device Token:\(deviceToken))

}

func applicationWillResignActive(application:UIApplication){


$ b func applicationDidEnterBackground(application:UIApplication){

}

func applicationWillEnterForeground(application:UIApplication){


$ b $ func applicationDidBecomeActive(application:UIApplication){


$ b func applicationWillTerminate(application:UIApplication){
$ (应用程序:UIApplication,didReceiveRemoteNotification,userInfo:[NSObject:AnyObject],fetchCompletionHandler completionHandler:(UIBackgroundFetchResult) - > b

$ b func application无效){
$ b $ print(MessageID:\(userInfo [gcm.messgae_id]!))//或gcm_etc ...

print(userInfo)





解决方案

更新:从Firebase 4.0.4开始,您可以按照 https://github.com/onmyway133/blog/issues/64



如何处理APNS设备标记



我一直在阅读发送通知给iOS上的用户段,但没有提及APNS设备令牌,这对于推送通知非常重要。因此,Firebase必须在引擎盖下做一些调整。实际上是这样。阅读后端文档下游邮件为我们提供了这个想法


Swizzling 禁用:映射您的APN令牌和注册令牌

 如果禁用方法调整,则需要将您的APN令牌显式映射到FCM注册令牌。覆盖

方法 didRegisterForRemoteNotificationsWithDeviceToken 检索
APNs令牌,然后调用 setAPNSToken



  func application(application:UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken:NSData){
FIRInstanceID.instanceID()。setAPNSToken(deviceToken,type:FIRInstanceIDAPNSTokenTypeSandbox)
}

我特别尽量避免混搭。阅读将iOS的GCM客户端应用程序迁移到Firebase云消息传递给我们如何禁用它

启用/禁用方法swizzling


方法与FCM一起使用可以简化您的客户端代码。
但是,对于不想使用它的开发者,FCM允许你在应用程序的Info.plist文件中添加
FIRMessagingAutoRegisterEnabledflag 来禁用
方法, b $ b将其值设置为NO(布尔值)。

  FCM调整会影响您如何处理默认注册标记,以及您处理下游消息回调。其中

适用,本指南提供迁移示例和
,但未启用方法调试。 / b>

显示代码

在您的 Podfile中

  pod'Firebase'
pod' FirebaseMessaging'

以下是完成的代码

<$ (应用程序:UIApplication,didFinishLaunchingWithOptions launchOptions:[NSObject:AnyObject]?) - > Bool {
FIRApp.configure()

NSNotificationCenter.defaultCenter()。addObserver(self,
selector:#selector(tokenRefreshNotification(_ :)),
name :kFIRInstanceIDTokenRefreshNotification,
object:nil)
}

//注意:禁用swizzling时需要使用
public func application(application:UIApplication,didRegisterForRemoteNotificationsWithDeviceToken deviceToken :NSData){

FIRInstanceID.instanceID()。setAPNSToken(deviceToken,type:FIRInstanceIDAPNSTokenType.Sandbox)
}

func tokenRefreshNotification(notification:NSNotification){
//注意:在这里可以是
let refreshedToken = FIRInstanceID.instanceID()。token()
print(InstanceID token:\(refreshedToken))

connectToFcm()
}

func connectToFcm(){
FIR Messaging.messaging()。connectWithCompletion {(error)in
if(error!= nil){
print(无法连接FCM。 \(error))
} else {
print(Connected to FCM。)
}
}
}

public func application(application:UIApplication,didReceiveRemoteNotification userInfo:[NSObject:AnyObject]){$ b $ print(userInfo)
}


Somewhat recently at the Google I/O event Google renovated Firebase and added a lot of new features, and touched up on the remaining ones. I have been trying to implement the iOS Push Notifications via Firebase into my app through the most basic level, so I created a very simple app that really does nothing besides receive remote push notifications. Inside of Firebase, I have uploaded my certificate and within Xcode my provisioning profiles have been added to both the target and project, and in Firebase I have uploaded the correct certificate. Below is the code contained inside of my AppDelegate.swift file but because my ViewController.swift is "empty," I did not include it. Although there are no crashes or runtime errors, when I load the app, I accept the notifications. Then, I exit the app and turn off my device. In Firebase, I send the notification to the correct app. After a couple of minutes, in Firebase it says the notification was "Completed". However, I never received the notification on the device. So, in conclusion, I need a solution to send Firebase this deviceToken and then use 'Firebase Notifications' to send the push notification Message. Any help for my code or in general would be greatly appreciated and I hope this helps future viewers. Thank you! My code in AppDelegate.swift :

import UIKit
import Firebase
import FirebaseMessaging

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

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

        FIRApp.configure()

        let notificationTypes : UIUserNotificationType = [UIUserNotificationType.Alert, UIUserNotificationType.Badge, UIUserNotificationType.Sound]

        let notificationSettings = UIUserNotificationSettings(forTypes: notificationTypes, categories: nil)

        application.registerForRemoteNotifications()
        application.registerUserNotificationSettings(notificationSettings)

        return true
    }

    func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {

        print("Device Token: \(deviceToken)")

    }

    func applicationWillResignActive(application: UIApplication) {

    }

    func applicationDidEnterBackground(application: UIApplication) {

    }

    func applicationWillEnterForeground(application: UIApplication) {

    }

    func applicationDidBecomeActive(application: UIApplication) {

    }

    func applicationWillTerminate(application: UIApplication) {

    }

    func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {

        print("MessageID : \(userInfo["gcm.messgae_id"]!)") // or gcm_etc...

        print(userInfo)

    }


}

解决方案

Updated: As of Firebase 4.0.4, you can follow https://github.com/onmyway133/blog/issues/64

HOW APNS DEVICE TOKEN IS HANDLED

I've been reading Send a Notification to a User Segment on iOS but there is no mention of APNS device token, which is crucial to push notifications.

So Firebase must be doing some swizzling under the hood. In fact it is. Reading backend documentation Downstream Messages gives us the idea

Swizzling disabled: mapping your APNs token and registration token

If you have disabled method swizzling, you'll need to explicitly map your APNs token to the FCM registration token. Override the

methods didRegisterForRemoteNotificationsWithDeviceToken to retrieve the APNs token, and then call setAPNSToken.

func application(application: UIApplication,
                   didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
  FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenTypeSandbox)
}

I particularly try to avoid swizzling as much as possible. Reading Migrate a GCM Client App for iOS to Firebase Cloud Messaging gives us how to do disable it

Enabling/disabling method swizzling

Method swizzling available with FCM simplifies your client code. However, for developers who prefer not to use it, FCM allows you to disable method swizzling by adding the FIRMessagingAutoRegisterEnabledflag in the app’s Info.plist file and setting its value to NO (boolean value).

FCM swizzling affects how you handle the default registration token, and how you handle downstream message callbacks. Where

applicable, this guide provides migration examples both with and without method swizzling enabled.

SHOW ME THE CODE

Have this in your Podfile

pod 'Firebase'
pod 'FirebaseMessaging'

Here is the completed code

import Firebase
import FirebaseMessaging

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

  NSNotificationCenter.defaultCenter().addObserver(self,
                                                   selector: #selector(tokenRefreshNotification(_:)),
                                                   name: kFIRInstanceIDTokenRefreshNotification,
                                                   object: nil)
}

// NOTE: Need to use this when swizzling is disabled
public func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {

  FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Sandbox)
}

func tokenRefreshNotification(notification: NSNotification) {
  // NOTE: It can be nil here
  let refreshedToken = FIRInstanceID.instanceID().token()
  print("InstanceID token: \(refreshedToken)")

  connectToFcm()
}

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

public func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
  print(userInfo)
}

这篇关于iOS Firebase推送通知:如何提供Firebase用户的设备令牌并发送通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆