SwiftUI 2 Firebase推送通知 [英] SwiftUI 2 Firebase push notification

查看:97
本文介绍了SwiftUI 2 Firebase推送通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在使用SwiftUI 2和新的应用程序生命周期构建iOS应用程序,尝试实现AppsDelegate和Firebase推送通知

So, I am building iOS app with SwiftUI 2 and new Application life cycle, trying to implement AppsDelegate and Firebase push notification

这里是我的代码示例

import SwiftUI

@main
struct App: App {
    
    @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
    
    var body: some Scene {
        WindowGroup {
            ContentView().environmentObject(AppSettings())
        }
    }
}

和AppDelegate

and AppDelegate

import Firebase
import FirebaseMessaging
import UserNotifications
import Foundation
import UIKit
class AppDelegate: NSObject {
    
    let gcmMessageIDKey = "gcm.message_id"
    
    private func setupFirebase(application: UIApplication) {
        FirebaseApp.configure()

        if #available(iOS 10.0, *) {
            // For iOS 10 display notification (sent via APNS)
            UNUserNotificationCenter.current().delegate = self

            let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
            UNUserNotificationCenter.current().requestAuthorization(
                options: authOptions,
                completionHandler: {_, _ in })
        } else {
            let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }
        Messaging.messaging().delegate = self
        application.registerForRemoteNotifications()
    }
    
}

extension AppDelegate: UIApplicationDelegate {
    
    func application(_ application: UIApplication,
                     didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
        setupFirebase(application: application)
        return true
    }
    
}

extension AppDelegate: MessagingDelegate {
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        print("Firebase registration token: \(fcmToken)")
    }
}

@available(iOS 10, *)
extension AppDelegate: UNUserNotificationCenterDelegate {
    
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        let userInfo = notification.request.content.userInfo
        
        // With swizzling disabled you must let Messaging know about the message, for Analytics
        // Messaging.messaging().appDidReceiveMessage(userInfo)
        
        // Print message ID.
        
        if let messageID = userInfo[gcmMessageIDKey] {
            print("Message ID: \(messageID)")
        }
        
        // Print full message.
        // print(userInfo)
        
        completionHandler([.banner, .badge, .sound])
    }
    
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo
        // Print message ID.
        
        if let messageID = userInfo[gcmMessageIDKey] {
            print("Message ID: \(messageID)")
        }
        
        // Print full message.
        print(userInfo)
        
        completionHandler()
    }
    
}

但是当我从Firebase控制台测试通知时,它没有来.

but when I’m testing notifications from firebase console, it's not coming.

推荐答案

我能够使您的代码正常工作.我认为Firebase有一个使 AppDelegate 混乱的问题.

I was able to get your code to work. I think that Firebase has an issue with swizzling the AppDelegate.

如果通过将键 FirebaseAppDelegateProxyEnabled 添加到 Info.plist ,将其设置为 Boolean 并将其设置为来禁用混淆否.

If you disable swizzling by adding the key FirebaseAppDelegateProxyEnabled to your Info.plist, making it a Boolean and setting it to NO.

然后在您的 AppDelegate 中添加以下内容,以便它在Firebase中注册APNS令牌.

Then in your AppDelegate you need to add the following, so that it registers the APNS token with Firebase.:

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    Messaging.messaging().apnsToken = deviceToken
}

要使Firebase Cloud Messaging正常工作,需要在APNS令牌及其令牌之间建立链接.如果没有建立链接,那么您将无法发送消息.

For Firebase Cloud Messaging to work it needs to make a link between the APNS token and its token. If no link is made then you will not be able to send messages.

请注意,通过禁用滚动,将具有某些属性您将需要手动更新.

您应该仔细阅读文档.在撰写此答案时,如果您禁用毛毛雨,您需要更新几个地方.

You should read the documentation carefully. At the time of writing this answer there are several places that you need to update if you disable swizzling.

AppDelegate中有 3 .上面显示了第一个,其他两个都在这里,它们与接收后台消息有关.

There are three in the AppDelegate. The first is shown above, the other two are here and are to do with receiving background messages.

您将以下行添加到委托方法中:

You are adding the following line to the delegate methods:

Messaging.messaging().appDidReceiveMessage(userInfo)

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

  // With swizzling disabled you must let Messaging know about the message, for Analytics
  Messaging.messaging().appDidReceiveMessage(userInfo) // <- this line needs to be uncommented

  // Print message ID.
  if let messageID = userInfo[gcmMessageIDKey] {
    print("Message ID: \(messageID)")
  }

  // Print full message.
  print(userInfo)
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                 fetchCompletionHandler completionHandler: @escaping (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

  // With swizzling disabled you must let Messaging know about the message, for Analytics
  Messaging.messaging().appDidReceiveMessage(userInfo) // <- this line needs to be uncommented

  // Print message ID.
  if let messageID = userInfo[gcmMessageIDKey] {
    print("Message ID: \(messageID)")
  }

  // Print full message.
  print(userInfo)

  completionHandler(UIBackgroundFetchResult.newData)
}

UNUserNotificationCenterDelegate中有两个.在您将以下行添加到委托方法的地方

There are two in the UNUserNotificationCenterDelegate. Where you add the follow line to the delegate methods

Messaging.messaging().appDidReceiveMessage(userInfo)

extension AppDelegate : UNUserNotificationCenterDelegate {

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

    // With swizzling disabled you must let Messaging know about the message, for Analytics
    Messaging.messaging().appDidReceiveMessage(userInfo) // <- this line needs to be uncommented

    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
      print("Message ID: \(messageID)")
    }

    // Print full message.
    print(userInfo)

    // Change this to your preferred presentation option
    completionHandler([[.alert, .sound]])
  }

  func userNotificationCenter(_ center: UNUserNotificationCenter,
                              didReceive response: UNNotificationResponse,
                              withCompletionHandler completionHandler: @escaping () -> Void) {
    let userInfo = response.notification.request.content.userInfo
    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
      print("Message ID: \(messageID)")
    }

    // With swizzling disabled you must let Messaging know about the message, for Analytics
    Messaging.messaging().appDidReceiveMessage(userInfo) // <- this line needs to be uncommented

    // Print full message.
    print(userInfo)

    completionHandler()
  }
}

以上代码摘自Firebase的Cloud Messaging文档.在代码注释中,他们非常清楚地指出,如果禁用了旋转功能,该怎么办.

This above code is lifted from Firebase's Cloud Messaging documentation. They are very clear in the comments of their code what needs to be done if you have disabled swizzling.

根据您项目中可能包含的其他Firebase模块,您可能需要手动更新其他值.在这里,您需要仔细检查文档和代码示例,以查看必须进行哪些更改.

Depending on which other Firebase modules you may include in your project you may have other values you need to update manually. This is where you will need to check carefully with the documentation and code samples to see what changes you have to make.

这篇关于SwiftUI 2 Firebase推送通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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