为啥我在 Swift 中没有收到来自 Firebase 的推送通知?

Posted

技术标签:

【中文标题】为啥我在 Swift 中没有收到来自 Firebase 的推送通知?【英文标题】:Why I do not get push notifications from Firebase in Swift?为什么我在 Swift 中没有收到来自 Firebase 的推送通知? 【发布时间】:2016-11-29 18:18:28 【问题描述】:

我在我的 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:FIRMessaging.messaging().connect (error) in if error != nil print("Unable to connect with FCM. \(error)") else print("Connected to FCM.") 添加到didFinishLaunchingWithOptions: 的末尾

    实现FIRMessageDelegate函数

    func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) 
    
        print(remoteMessage.appData)
    
    

    FIRMessaging.messaging().appDidReceiveMessage(userInfo)添加到func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @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)

【讨论】:

什么也没有发生。 Firebase 写发送成功,但我什么也没得到 =/ 您可以从 Firebase 控制台截屏您的“撰写消息”屏幕吗?您是否正确设置了 FCM 注册令牌? 您是否从 XCode 控制台获得了“已连接到 FCM。”? 好吧,酷。这意味着您在 Firebase 控制台上的配置正在运行。损坏的部分可能是您的应用没有收到来自 APNS 服务器的通知。那么您是否启用了“推送通知”@XCode,创建了一个开发配置文件@Developer.apple.com? 所以,我的推送通知是有效的,我刚刚注意到了。但它在后台模式下不起作用=/【参考方案2】:

对于仍在寻找的人,请在此处查看最后一个答案:ios10, Swift 3 and Firebase Push Notifications (FCM)

检查您的推送通知权利并将其打开。目标 > 功能 > 推送通知。

【讨论】:

以上是关于为啥我在 Swift 中没有收到来自 Firebase 的推送通知?的主要内容,如果未能解决你的问题,请参考以下文章

为啥我的 iPhone 没有收到任何通知?

为啥我在 iOS 上从 Swift 调用服务时收到 SSL 错误?

为啥 ZeroMQ 服务器没有收到来自客户端的任何请求?

Swift 不会打印来自通知委托的有效负载

为啥我在尝试列出会话时收到来自 tmux 的“连接服务器失败”消息?

为啥我在尝试在 iOS Swift 中向服务器发出 post 请求时收到此错误:在展开 Optional 值时意外发现 nil?