Уведомления Pu sh не работают - Firebase Cloud Messaging - PullRequest
0 голосов
/ 30 апреля 2020

Я проверил свой код, и я не уверен, что я что-то упускаю, когда я отправляю сообщение, которое бросило firebase, которое он отправляет, но на моем симуляторе это не показывает уведомление. Я использую apnsKey. Я действительно понятия не имею, что происходит неправильно. там в любом случае, чтобы пристрелить проблемы или обнаружить, что пережил это на некоторое время сейчас

import UIKit
import Firebase
import Stripe
import UserNotifications
import FirebaseMessaging


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

    initializeStripe()


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

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

    //==========================


    return true
}







//MARK:STRIPE
//=====================================================================
func initializeStripe(){
    STPPaymentConfiguration.shared().publishableKey = Constants.publishableKey

    stripeClient.sharedClient.baseUrlString = Constants.baseUrlString

}








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





  }
   @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 {

func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
    print("token fcm: \(fcmToken) boom")

    let dataDict: [String : String] = ["token" : fcmToken]
    NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil,  userInfo: dataDict)

  }

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


   }

1 Ответ

1 голос
/ 30 апреля 2020

Начиная с стабильной версии Xcode 11.3. *, Для проверки уведомления pu sh на iOS вам необходимо реальное устройство. Невозможно проверить на симуляторе. Тем не менее, вы можете скачать бета-версию Xcode 11.4, если у вас нет под рукой реального устройства.

Вы можете найти следующее в официальных заметках о выпуске Xcode 11.4 в разделе Simulator -> New Особенности

Симулятор поддерживает моделирование удаленных уведомлений pu sh, включая уведомления о получении фонового содержимого. В Симуляторе перетащите файл APNs на целевой симулятор. Файл должен быть JSON с допустимой нагрузкой Apple Pu sh Notification Service, включая ключ «aps». Он также должен содержать «Целевой пакет симулятора» верхнего уровня со строковым значением, соответствующим идентификатору пакета целевого приложения.

...