【问题标题】:Push Notification from firebase console iOS 12.2 not working来自 Firebase 控制台 iOS 12.2 的推送通知不起作用
【发布时间】:2019-09-14 12:39:44
【问题描述】:

推送通知根本不起作用。到目前为止,我已经尝试了所有可能的措施:

这是我尝试过的代码:

didFinishLaunchingWithOptions

FirebaseApp.configure()

if #available(iOS 10.0, *) {
    let center = UNUserNotificationCenter.current()
    center.delegate = self
    center.requestAuthorization(options: [.badge, .alert, .sound]) {
        (granted, error) in
        if granted {
            DispatchQueue.main.async {
                application.registerForRemoteNotifications()
                //UIApplication.shared.registerForRemoteNotifications()
            }
        } else {
            //print("APNS Registration failed")
            //print("Error: \(String(describing: error?.localizedDescription))")
        }
    }
} else {
    let type: UIUserNotificationType = [UIUserNotificationType.badge, UIUserNotificationType.alert, UIUserNotificationType.sound]
    let setting = UIUserNotificationSettings(types: type, categories: nil)
    application.registerUserNotificationSettings(setting)
    application.registerForRemoteNotifications()
    //UIApplication.shared.registerForRemoteNotifications()
}

然后是注册和失败方法:

private func application(application: UIApplication,
                 didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
    Messaging.messaging().apnsToken = deviceToken as Data
    print("Registered Notification")
}

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {

        print(error.localizedDescription)
        print("Not registered notification")
}

@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {

    // Receive displayed notifications for iOS 10 devices.
    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["gcm.message_id"] {
            print("Message ID: \(messageID)")
        }

        // Print full message.
        print(userInfo)

        // Change this to your preferred presentation option
        completionHandler([])
    }

    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["gcm.message_id"] {
            print("Message ID: \(messageID)")
        }

        // Print full message.
        print(userInfo)

        completionHandler()
    }
}

注意:

  • 我已经在真机上试过了,目前没有推送通知。
  • 我在打开推送通知后仔细检查了证书并重新生成了配置文件 能力。
  • 我还添加了后台模式 -> 远程通知开启。
  • 我尝试过使用旧版构建也没有成功。
  • 我尝试重新安装应用程序很多次都不起作用。
  • FirebaseAppDelegateProxyEnabled 在 plist 中设置为 NO 仍然没有运气。
  • 还更新了 pod,但仍然没有运气。
  • .p12 证书位于 firebase 控制台,但仍无法正常工作。

从过去 1 周开始尝试使用 Apple 密钥使用不同身份验证方法的不同项目,我也尝试过仍然没有运气。

【问题讨论】:

  • 您是否检查过在单个设备令牌上发送 Firebase 测试通知?
  • @Nikung 我正在尝试使用 firebase 发送消息,但暂时不支持后端,无法正常工作,是的,我正在尝试使用多个令牌而不是单个令牌。
  • 在这种情况下你会得到什么输出:如果授予 { DispatchQueue.main.async { application.registerForRemoteNotifications() //UIApplication.shared.registerForRemoteNotifications() } } else { print("APNS 注册失败") print("错误:(String(描述:错误?.localizedDescription))") }
  • @Nikunj 堆栈上有人说 application.registerForRemoteNotifications() 应该在主线程上而不是在后台线程上,输出是它正在被授予并且成功代码正在运行。

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


【解决方案1】:

这是我用来生成推送通知的代码,希望对您有所帮助。

将以下整个代码放入你的 appdelegate 中。

导入库

 import Firebase
import FirebaseMessaging
import UserNotifications
import FirebaseInstanceID
import UserNotifications

将 MessagingDelegate 添加到您的 appdelegate。

然后

在 didFinishLaunchingWithOptions 中

 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: { (bool, err) in

        })

    } else {

        let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
        application.registerUserNotificationSettings(settings)

    }

    application.registerForRemoteNotifications()
    UIApplication.shared.applicationIconBadgeNumber = 0

    FirebaseApp.configure()
    // [START set_messaging_delegate]
    Messaging.messaging().delegate = self
    let token = Messaging.messaging().fcmToken
    print("FCM token: \(token ?? "")")

然后添加这两个函数

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)

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

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

    if let msg = userInfo["desc"] as? String
    {
        let title = userInfo["noti_title"] as? String
        createNotification(message: msg, title: title ?? "" )

    }

    // Print full message.
    print(userInfo)

    completionHandler(UIBackgroundFetchResult.newData)
}


func createNotification(message: String, title: String) {

    let content = UNMutableNotificationContent()
    content.title =  title
    content.body = message


    let triger = UNTimeIntervalNotificationTrigger(timeInterval: 2, repeats: false )
    let request = UNNotificationRequest(identifier: "TextMessage", content: content, trigger: triger)



    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}

然后添加这些函数就可以得到FCMToken

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        print("APNs token retrieved: \(deviceToken)")

        // With swizzling disabled you must set the APNs token here.
        if let refreshedToken = InstanceID.instanceID().token() {
            print("InstanceID token: \(refreshedToken)")

        }
        let tokenT = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
        print(tokenT)
        guard let token = InstanceID.instanceID().token() else {return}
        AppDelegate.DEVICEID = token
        print(token)
        UserDefaults.standard.set(token, forKey: "token")

        connectToFCM()


    }
    func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
        guard  let newToken = InstanceID.instanceID().token() else {return}
        AppDelegate.DEVICEID = newToken
        UserDefaults.standard.set(newToken, forKey: "token")

        connectToFCM()
    }
    func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
        print("Received data message: \(remoteMessage.appData)")
        print(remoteMessage.appData["notification"]!)
//        let info = response.notification.request.content.userInfo

//        if let message = info["messages"] {
//            print(message)
//        }
    }
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        print("Firebase registration token: \(fcmToken)")
        UserDefaults.standard.set(fcmToken, forKey: "token")




    }

然后在您的应用委托中添加以下扩展

extension AppDelegate : UNUserNotificationCenterDelegate {

    // Receive displayed notifications for iOS 10 devices.
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification,                            withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

        let userInfo = notification.request.content.userInfo

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

        print(userInfo)

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


    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        let application = UIApplication.shared

        if(application.applicationState == .active){
            print("user tapped the notification bar when the app is in foreground")

            window = UIWindow(frame: UIScreen.main.bounds)
            window?.makeKeyAndVisible()

            //        let layout = UICollectionViewFlowLayout()
            window?.rootViewController = UINavigationController(rootViewController: NotificationViewController())


        }

        if(application.applicationState == .inactive)
        {
            print("user tapped the notification bar when the app is in background")
            window = UIWindow(frame: UIScreen.main.bounds)
            window?.makeKeyAndVisible()

            //        let layout = UICollectionViewFlowLayout()
            window?.rootViewController = UINavigationController(rootViewController: NotificationViewController())

        }

        /* Change root view controller to a specific viewcontroller */
        // let storyboard = UIStoryboard(name: "Main", bundle: nil)
        // let vc = storyboard.instantiateViewController(withIdentifier: "ViewControllerStoryboardID") as? ViewController
        // self.window?.rootViewController = vc

        completionHandler()
    }

    func connectToFCM()
    {
        Messaging.messaging().shouldEstablishDirectChannel = true
    }
    func initializeNotificationServices() -> Void {
        let settings = UIUserNotificationSettings(types: [.sound, .alert, .badge], categories: nil)
        UIApplication.shared.registerUserNotificationSettings(settings)

        // This is an asynchronous method to retrieve a Device Token
        // Callbacks are in AppDelegate.swift
        // Success = didRegisterForRemoteNotificationsWithDeviceToken
        // Fail = didFailToRegisterForRemoteNotificationsWithError
        UIApplication.shared.registerForRemoteNotifications()
    }

}

希望对您有所帮助。

【讨论】:

  • 所以你是说当我处于开发阶段时,我仍然需要向 Firebase 提供生产 .p12 证书以使其正常工作?
  • noo 我只是说使用有问​​题的代码,它的工作完美。对于证书密钥,如果您想发布您的应用程序,您应该使用生产密钥。开发证书不适用于已发布或已发布的应用,因为生产证书同时适用于开发和发布场景。
  • 你能给我链接你说的怎么样?我也试过生产证书?还是不行?
  • 我已经添加了我的代码并更新了我的答案,请将您的代码与我的代码进行匹配和比较,这将对您有所帮助....手指交叉... :) 并测试代码转到 firebase 消息传递和如果您在屏幕上弹出相同的生成通知,则从那里生成通知,然后它的工作
  • 仍然无法使用,现在尝试使用 APN 密钥也仍然无法使用。
猜你喜欢
  • 2019-09-22
  • 1970-01-01
  • 1970-01-01
  • 2021-05-02
  • 1970-01-01
  • 2018-05-01
  • 2019-04-19
  • 2020-01-31
  • 1970-01-01
相关资源
最近更新 更多