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

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

问题描述

最近在 Google I/O 活动中,Google 翻新了 Firebase &添加了许多新功能,并对其余功能进行了改进.我一直在尝试通过最基本的级别通过 Firebase 将 iOS 推送通知实现到我的应用程序中,所以我创建了一个非常简单的应用程序,除了接收远程推送通知之外,它真的什么都不做.

Somewhat recently at the Google I/O event Google renovated Firebase & 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.

在 Firebase 中,我上传了我的证书,在 Xcode 中我的配置文件已添加到目标和项目中,并且在 Firebase 中我上传了正确的证书.下面是包含在我的 AppDelegate.swift 文件中的代码,但因为我的 ViewController.swift 是空的",所以我没有包含它.

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.

虽然没有崩溃或运行时错误,但当我加载应用程序时,我接受了通知.然后,我退出应用程序并关闭我的设备.在 Firebase 中,我将通知发送到正确的应用程序.几分钟后,Firebase 显示通知已完成".

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".

但是,我从未在设备上收到通知.因此,总而言之,我需要一个解决方案来向 Firebase 发送此 deviceToken,然后使用Firebase 通知"发送推送通知消息.

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.

对我的代码或一般情况的任何帮助将不胜感激,我希望这有助于未来的观众.谢谢!我在 AppDelegate.swift 中的代码:

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)

    }


}

推荐答案

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

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

APNS 设备令牌的处理方式

我一直在阅读 在 iOS 上向用户群发送通知 但没有提到对推送通知至关重要的 APNS 设备令牌.

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.

所以 Firebase 必须在幕后进行一些调整.事实上它是.阅读后端文档下游消息给了我们这个想法

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

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

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

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

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

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

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

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

启用/禁用方法调配

FCM 提供的方法混合可简化您的客户端代码.但是,对于不喜欢使用它的开发人员,FCM 允许您通过添加禁用方法调配FIRMessagingAutoRegisterEnabledflag 在应用程序的 Info.plist 文件和将其值设置为 NO(布尔值).

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.

给我看代码

在你的 Podfile

pod 'Firebase'
pod 'FirebaseMessaging'

这是完整的代码

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天全站免登陆