Почему я не могу получить push-сообщение в Swift5? - PullRequest
0 голосов
/ 24 сентября 2019

Я сейчас пытаюсь получить push-сообщение.Однако вы не можете получить push-сообщение.Чего мне не хватает?

AppDelegate

import UIKit
import UserNotifications
import Firebase
import FirebaseMessaging

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate  {

    var window: UIWindow?



    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        self.window = UIWindow(frame: UIScreen.main.bounds)
        // Override point for customization after application launch.
        //create the notificationCenter
        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: {_, _ in })
        } else {
            let settings: UIUserNotificationSettings =
                UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }

        application.registerForRemoteNotifications()
        FirebaseApp.configure()
        Messaging.messaging().delegate = self



        return true
    }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let token = deviceToken.map{ String(format: "%02x", $0) }.joined()
        Log.Info("Registration succeeded!")
        Log.Info("Token: \(token)")
        LocalStorage.set(token, "dacDeviceToken")
        Messaging.messaging().apnsToken = deviceToken
        InstanceID.instanceID().instanceID { (result, error) in
          if let error = error {
            Log.Error("Error fetching remote instance ID: \(error)")
          } else if let result = result {
            Log.Info("Remote instance ID token: \(result.token)")
          }
        }
    }

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        Log.Warning("Registration failed!")
    }

    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"] {
        Log.Info("Message ID: \(messageID)")
      }

      // Print full message.
      Log.Info(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)

      // Print message ID.
      if let messageID = userInfo["gcmMessageIDKey"] {
        Log.Info("Message ID: \(messageID)")
      }

      // Print full message.
      Log.Info(userInfo)

      completionHandler(UIBackgroundFetchResult.newData)
    }


    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }

    func getNotificationSettings() {
      UNUserNotificationCenter.current().getNotificationSettings { settings in
        print("Notification settings: \(settings)")
        guard settings.authorizationStatus == .authorized else { return }
        DispatchQueue.main.async {
          UIApplication.shared.registerForRemoteNotifications()
        }
      }
    }


}

@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
        // Print message ID.
        Log.Info("Message ID: \(userInfo["gcm.message_id"]!)")

        // Print full message.
        print("%@", userInfo)
        Log.Info(userInfo)
    }

}

extension AppDelegate : MessagingDelegate {
    // Receive data message on iOS 10 devices.
    func applicationReceivedRemoteMessage(_ remoteMessage: MessagingRemoteMessage) {
        print("%@", remoteMessage.appData)
    }

    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        Log.Info("Firebase registration token: \(fcmToken)")

        let dataDict:[String: String] = ["token": fcmToken]
        NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
        // TODO: If necessary send token to application server.
        // Note: This callback is fired at each app startup and whenever a new token is generated.
    }
}

мой журнал

2019-09-24 19: 31: 46.519806 + 0900 тест [586: 74065] -

[I-ACS036002] Отчеты экрана аналитики включены.

Вызов + [FIRAnalytics setScreenName: setScreenClass:] для установки экрана

name или переопределить имя класса экрана по умолчанию.Чтобы отключить экранные отчеты

, установите для флага FirebaseScreenReportingEnabled значение NO (логическое значение)

в Info.plist 2019-09-24 19: 31: 46.756433 + 0900 test [586: 74071]

6.9.0 - [Firebase / Messaging] [I-FCM001000] Включен прокси-сервер удаленных уведомлений FIRMessaging, который будет обрабатывать обработчики удаленных уведомлений

.Если вы предпочитаете вручную интегрировать Firebase Messaging,

добавьте «FirebaseAppDelegateProxyEnabled» в ваш Info.plist и установите для

значение NO.Следуйте инструкциям по адресу:

, чтобы обеспечить правильную интеграцию.2019-09-24 19: 31: 46.759687 + 0900

test [586: 74071] 6.9.0 - [Firebase / Analytics] [I-ACS023007] Аналитика v.60102000 запущена 2019-09-24 19:31: 46.760699 + 0900 test [586: 74071] 6.9.0 - [Firebase / Analytics] [I-ACS023008] Чтобы включить ведение журнала отладки, установите следующий аргумент приложения: -FIRAnalyticsDebugEnabled INFO: 2019-09-24 10:31:46 +0000 - Обмен сообщениями AppDelegate.swift (_: didReceiveRegistrationToken :) [Строка: 196]

Токен регистрации Firebase: dZ4US-5dJqk: APA91bF0 - **************** INFO: 2019-09-24 10:31:46 +0000 - Приложение AppDelegate.swift (_: didRegisterForRemoteNotificationsWithDeviceToken :) [Строка: 82] Регистрация прошла успешно!ИНФОРМАЦИЯ: 2019-09-24 10:31:46 +0000 - AppDelegate.swift

application (: didRegisterForRemoteNotificationsWithDeviceToken :) [Строка: 83] Токен: 213eba827 ******************************* ИНФОРМАЦИЯ: 2019-09-24 10:31:46 +0000 - приложение AppDelegate.swift (: didRegisterForRemoteNotificationsWithDeviceToken :) [Line: 90] Токен идентификатора удаленного экземпляра: dZ4US-5dJqk: APA91bF0-77 ***********

2019-09-24 19: 31: 46.921546 + 0900 тест [586: 74071][MC] Контейнер системной группы для пути systemgroup.com.apple.configurationprofiles: /private/var/containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles 2019-09-24 19: 31: 46.923537 + 0900 test [586:74071] [MC] Чтение из общедоступных действующих пользовательских настроек.

Отправить тест FCM gegg

fcm

back

test Я ничего не понимаю.Мое приложение не получает push-сообщения, будь то на переднем плане или в фоновом режиме.

Пожалуйста, помогите мне.

Токен, который вы добавили на рисунке, является значением токена устройства.Значения токенов отображаются в журнале.

РЕДАКТИРОВАТЬ

Я видел ответ и следовал ему, но он не работает.

Ответы [ 2 ]

1 голос
/ 24 сентября 2019

Я видел ответ и следовал ему, но он не работает.Однако, когда вы добавили новый проект на Fire Base, снова добавили приложение iOS и попытались, он был успешным.Я не уверен, что не так.Была ли это проблема с моим кодом? Я подумал, но когда я использовал код в вопросе, это тоже сработало.Я просто создал и добавил новый проект для своего решения.

1 голос
/ 24 сентября 2019

Можете ли вы поместить GoogleService-Info.plist файл в свой проект?

Попробуйте это в моем коде 100% работает

 import Firebase
    import FirebaseCore
    import FirebaseMessaging
    import UserNotifications
    import UserNotificationsUI

    @UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate , MessagingDelegate{

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


            Messaging.messaging().delegate = self
            FirebaseApp.configure()

            //Register App For Push Notification
            self.registerAppForPushNotificaition()
            application.registerForRemoteNotifications()

            return true
        }

     func registerAppForPushNotificaition(){
            if #available(iOS 10.0, *) {
                let center = UNUserNotificationCenter.current()
                let inviteCategory = UNNotificationCategory(identifier: "Notification", actions: [], intentIdentifiers: [], options: UNNotificationCategoryOptions.customDismissAction)
                let categories = NSSet(objects: inviteCategory)

                center.delegate = self
                center.setNotificationCategories(categories as! Set<UNNotificationCategory>)
                center.requestAuthorization(options: [.sound, .badge, .alert], completionHandler: { (granted, error) in
                    if !(error != nil){
                        DispatchQueue.main.async(execute: {
                            UIApplication.shared.registerForRemoteNotifications()
                        })
                    }
                })
            } else {
                UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types:[.sound , .alert , .badge] , categories: nil))
                UIApplication.shared.registerForRemoteNotifications()
            }


        }
     @available(iOS 10.0, *)
        func userNotificationCenter(_ center: UNUserNotificationCenter,
                                    willPresent notification: UNNotification,
                                    withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
        {
    completionHandler(.alert)
    }
     func application(_ application: UIApplication,
                         didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {


            Auth.auth().setAPNSToken(deviceToken, type: AuthAPNSTokenType.sandbox)
            Messaging.messaging().apnsToken = deviceToken




            let token = InstanceID.instanceID().token()

            if token != nil {
                fcmID = token!
            }


        }

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

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

            NSLog("Failed to get Access Token: \(error)")

        }
     func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                         fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
     if Auth.auth().canHandleNotification(userInfo) {
                completionHandler(UIBackgroundFetchResult.noData)
                return
            }

            completionHandler(UIBackgroundFetchResult.newData)
        }
     func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {



           print("fcmToken \(fcmToken)")
        }

        func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
            print("remort \(remoteMessage.appData)")
        }
...