ios - 为什么我在 Swift 中收不到来自 Firebase 的推送通知?

标签 ios swift firebase apple-push-notifications firebase-cloud-messaging

我在 AppDelegate 中设置了此代码:

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, FIRMessagingDelegate { 

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    if #available(iOS 10.0, *) {
        let authOptions: UNAuthorizationOptions = [.Alert, .Badge, .Sound]
        UNUserNotificationCenter.currentNotificationCenter().requestAuthorizationWithOptions(authOptions, completionHandler: { (granted: Bool, error: NSError?) in
            // For iOS 10 display notification (sent via APNS)
            UNUserNotificationCenter.currentNotificationCenter().delegate = self
            // For iOS 10 data message (sent via FCM)
            FIRMessaging.messaging().remoteMessageDelegate = self
        })
    } else {
        let settings: UIUserNotificationSettings =
            UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
        application.registerUserNotificationSettings(settings)
    }

    application.registerForRemoteNotifications()

    application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [.Alert, .Sound, .Badge], categories: nil))
}

还有这部分:

internal func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
    print(userInfo)
    // 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

    // Print message ID.
    print("Message ID: \(userInfo["gcm.message_id"]!)")

    // Print full message.
    print(userInfo)
}

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
                   fetchCompletionHandler completionHandler: (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

    // Print message ID.
    print("Message ID: \(userInfo["gcm.message_id"]!)")

    // Print full message.
    print(userInfo)
}

@available(iOS 10.0, *)
func userNotificationCenter(center: UNUserNotificationCenter, willPresentNotification notification: UNNotification, withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void) {
    //Handle the notification
}

@available(iOS 10.0, *)
func userNotificationCenter(center: UNUserNotificationCenter, didReceiveNotificationResponse response: UNNotificationResponse, withCompletionHandler completionHandler: () -> Void) {
    //Handle the notification
}

我还将开发 APN 上传到 Apple Developers 中。在 Firebase 控制台中,它写道通知已成功发送,但我没有收到任何推送通知。谁能帮我找出我的错误在哪里?

我已经为此工作了3天。搜索了很多,但一无所获。

最佳答案

  1. FIRApp.configure() 添加到 didFinishLaunchingWithOptions:
  2. 添加FIRMessaging.messaging().connect {(错误)于 如果错误!= nil { print("无法与 FCM 连接。\(错误)") } 别的 { print("已连接至 FCM。") }didFinishLaunchingWithOptions:
  3. 的末尾
  4. 实现FIRMessageDelegate函数

    func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
    
        print(remoteMessage.appData)
    }
    
  5. FIRMessaging.messaging().appDidReceiveMessage(userInfo)添加到func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler 完成处理程序:@escaping (UIBackgroundFetchResult) -> Void)

最终代码应如下所示:

import UIKit
import Firebase
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, FIRMessagingDelegate {

var window: UIWindow?


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    FIRApp.configure()

    if #available(iOS 10.0, *) {
        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(
            options: authOptions,
            completionHandler: {_, _ in })

        // For iOS 10 display notification (sent via APNS)
        UNUserNotificationCenter.current().delegate = self
        // For iOS 10 data message (sent via FCM)
        FIRMessaging.messaging().remoteMessageDelegate = self
    } else {
        let settings: UIUserNotificationSettings =
            UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
        application.registerUserNotificationSettings(settings)
    }


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

    return true
}

func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {

    print("applicationReceivedRemoteMessage ")
    print(remoteMessage.appData)
}

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

    // Print message ID.
    print("Message ID: \(userInfo["gcm.message_id"]!)")

    // 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

    // Print message ID.
    print("Message ID: \(userInfo["gcm.message_id"]!)")

    // Print full message.
    print(userInfo)

    FIRMessaging.messaging().appDidReceiveMessage(userInfo)
}

关于ios - 为什么我在 Swift 中收不到来自 Firebase 的推送通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40872966/

相关文章:

ios - 针对区域本地化 iPhone 应用程序

json - Swift 如何从 JSON 中提取 "sort"字典以在时间序列中绘制它?

ios - 如何将 MapView 中的注释链接到其调用引脚

ios - CLLocationManager 区域监控 : Detect Arrival in Suspended State

firebase - 如果我在 Google-Service-info.plist 中将 IS_GCM_ENABLED 键禁用为 false 会发生什么

javascript - Firebase Auth setCustomClaims() 不起作用

iphone - 根据字符串内容更改字符串; (NSExpression 小数问题)。 Xcode

ios - 在后台检测主页按钮长按事件

ios - 显示在 JSQMessagesViewController 中发送的视频的图像预览

android - 在MVVM Android中使用Firebase注销的正确方法