【问题标题】:Push notifications not working - Firebase Cloud Messaging推送通知不起作用 - Firebase 云消息传递
【发布时间】:2020-08-14 10:10:48
【问题描述】:

我检查了我的代码,我不确定我发送消息时是否遗漏了任何东西,抛出了它发送的 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)")
}


   }

【问题讨论】:

    标签: swift firebase firebase-cloud-messaging


    【解决方案1】:

    从 Xcode 稳定版 11.3.* 开始,要在 iOS 上测试推送通知,您需要一台真实设备。无法在模拟器上进行测试。不过,如果手边没有真机,可以下载 Xcode 11.4 beta。

    您可以在 Xcode 11.4 的官方 release notes 的 Simulator -> New Features 部分下找到以下内容

    模拟器支持模拟远程推送通知,包括 背景内容获取通知。在模拟器中,拖放一个 APNs 文件到目标模拟器。该文件必须是 JSON 文件 有效的 Apple 推送通知服务负载,包括“aps” 钥匙。它还必须包含一个顶级“模拟器目标包”,其中包含 与目标应用程序包标识符匹配的字符串值。

    【讨论】:

    • AHH 谢谢你让我知道我确实有一部 iPhone,但我错误地将它更新到 iOS 13.4,现在 Xcode 不允许我连接它,因为它太超前了。它建议升级 Xcode,但我有最新版本的 Xcode,这意味着苹果尚未发布允许 iOS 13.4 的版本
    猜你喜欢
    • 1970-01-01
    • 2016-12-13
    • 1970-01-01
    • 2017-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多