Не получает уведомление от FCM на IOS - PullRequest
0 голосов
/ 10 января 2020

Эй, ребята, я настроил приложение для получения сообщений FCM, но не получаю уведомление в IOS, я включил все запрошенные профили обеспечения в консоли разработчика приложения, но все еще возникают проблемы с получением.

Я пытаюсь сделать это на iPhone 8, я пробовал это на iPhone X-симуляторе, и он получил сообщение, однако x-код дает мне cra * sh, потому что FCM не поддерживается на симуляторах. Есть ли способ включить FCM на симуляторах для iPhone?

Редактировать Я заметил сообщение, указывающее, что я получаю сообщение, но в моем списке p был параметр, который не был установлен для фоновых уведомлений, которые я с тех пор добавил в список p enter image description here

Не получаю предупреждение, но все равно не получаю уведомления.

Вот мой текущий делегат приложения

//
//  AppDelegate.swift
//  RodeoMonkey
//
//  Created by Douglas Ray on 8/10/19.
//  Copyright © 2019 rodeomonkeyllc. All rights reserved.
//

import UIKit
import Firebase
import FirebaseMessaging


let userDefaults = UserDefaults.standard


@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?
let gcmMessageIDKey = "gcm.message_id"


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

    if (!userDefaults.bool(forKey: "hasRunBefore")) {
        print("The app is launching for the first time. Setting UserDefaults...")

        do {
            try Auth.auth().signOut()
            let storyBoard : UIStoryboard = UIStoryboard(name : "SplashScreenStoryboard",bundle: nil)
            let newViewController = storyBoard.instantiateViewController(withIdentifier:"SplashScreenViewController")
            newViewController.modalPresentationStyle = .fullScreen
            UIApplication.shared.windows.first?.rootViewController = newViewController
         } catch {}
         userDefaults.set(true, forKey: "hasRunBefore")
         userDefaults.synchronize() // This forces the app to update userDefaults

        // Run code here for the first launch

    } else {
        print("The app has been launched before. Loading UserDefaults...")
        // Run code here for every other launch but the first

        Messaging.messaging().delegate = self


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


        // this line is important
        self.window = UIWindow(frame: UIScreen.main.bounds)
        let storyboard = UIStoryboard.init(name: "Home", bundle: nil)
        let viewController = storyboard.instantiateViewController(withIdentifier: "HomeController") as! HomeController
        let navigationController = UINavigationController.init(rootViewController: viewController)
        self.window?.rootViewController = navigationController
        self.window?.makeKeyAndVisible()

    }

    return true
 }

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 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)
  // Print message ID.
  if let messageID = userInfo[gcmMessageIDKey] {
    print("Message ID: \(messageID)")
  }

  // Print full message.
  print(userInfo)

  completionHandler(UIBackgroundFetchResult.newData)
  }
  }



  // [START ios_10_message_handling]
  @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[gcmMessageIDKey] {
  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[gcmMessageIDKey] {
  print("Message ID: \(messageID)")
}

// Print full message.
print(userInfo)

completionHandler()
}
}

extension AppDelegate : MessagingDelegate {
// [START refresh_token]
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
print("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.


}

func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
print("Received data message: \(remoteMessage.appData)")
}
  // [END ios_10_data_message]
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...