我的应用程序正在实施Firebase Cloud消息传递来发送通知。每当我使用Firebase控制台测试Firebase通知时,将通过将显示userNotificationCenter函数和didReceiveRemoteNotification处理通知,而不是由Firebase applicationReceivedRemoteMessage函数处理通知,我是否缺少某些东西?另外,当我尝试打印刚从Firebase发出的通知时,userNotification函数没有任何数据。这是我的设置:
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, FIRMessagingDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().delegate = self
FIRMessaging.messaging().remoteMessageDelegate = self
FIRApp.configure()
registerForFireBaseNotifications()
//Other set up variables
connectToFcm()
return true
}
func registerForFireBaseNotifications(){
let authOptions: UNAuthorizationOptions = [.alert, .sound, .badge]
UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: {_, _ in })
application.registerForRemoteNotifications()
}
func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
print("Recieved remote firebase notification: %@", remoteMessage.appData)
}
func tokenRefreshNotification(notification: NSNotification) {
let refreshedToken = FIRInstanceID.instanceID().token()
print("FCM: Connected to FCM. Token : \(String(describing: refreshedToken))")
connectToFcm()
}
func connectToFcm() {
// Won't connect since there is no token
guard FIRInstanceID.instanceID().token() != nil else {
print("FCM: Token does not exist.")
return
}
// Disconnect previous FCM connection if it exists.
FIRMessaging.messaging().disconnect()
FIRMessaging.messaging().connect { (error) in
if error != nil {
print("FCM: Unable to connect with FCM. \(error.debugDescription)")
} else {
print("Connected to FCM.")
}
}
}
//Non firebase notifications
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (_ options: UNNotificationPresentationOptions) -> Void) {
//do something with notifications that came while on foreground
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
//do something with notifications that came from background
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.sandbox)
}
答案 0 :(得分:0)
我能够不断挖掘并找到所需的答案。对于任何为此感到困惑并了解Firebase通知如何与IOS一起工作的人。上面的设置代码正确无误。我遇到的主要问题是通知没有通过Firebase函数applicationReceivedRemoteMessage处理。根据我的理解,这是不正确的! Firebase控制台允许您仅将消息作为通知发送!这意味着您的应用将通过apns收到通知!如果要触发applicationReceivedRemoteMessage函数,则需要将消息作为数据json对象发送。您可以通过邮递员执行以下操作:Unable to send data message using firebase console。希望这会有所帮助!