Push-уведомление из Firebase консоли iOS 12.2 не работает - PullRequest
0 голосов
/ 25 апреля 2019

Push-уведомления не работают вообще. Я перепробовал все возможные меры:

Это код, который я пробовал:

В 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()
    }
}

Примечание:

  • Я пробовал на реальном устройстве пока нет push-уведомлений.
  • Я дважды проверил сертификаты и восстановил файл инициализации после включения push-уведомлений в Возможности.
  • Я также добавил фоновые режимы -> удаленные уведомления включены.
  • Я пробовал с легаси билд тоже не повезло.
  • Я много раз пытался переустановить приложения, но не работал.
  • Для FirebaseAppDelegateProxyEnabled в plist установлено значение NO, но все равно не повезло.
  • Также обновил стручки до сих пор не повезло.
  • .p12 сертификат находится на консоли Firebase, все еще не работает.

Попытка за последние 1 неделю с различными проектами с разными методами аутентификации с ключом Apple, я тоже все еще не пытался.

1 Ответ

1 голос
/ 25 апреля 2019

вот код, который я использовал для создания push-уведомлений, надеюсь, это поможет вам.

поместите весь следующий код в ur 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()
    }

}

, надеясь, что это поможет вам.

...