Swift Firebase iOS didReceiveRemoteNotification 从不调用

Swift Firebase iOS didReceiveRemoteNotification never calling

我在 iOS 应用程序中使用 Firebase 并在服务器上使用 Azure 通知中心发送通知。 我已经制作了 this and this 篇文章中所有需要的东西。 这是我的 AppDelegate.swift 代码:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    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
}

在此之后,我调用服务器端在 Azure 通知中心注册我的通知应用程序。以下是我获取设备令牌的方式:

InstanceID.instanceID().instanceID { (result, error) in
      if let error = error {
        print("Error fetching remote instance ID: \(error)")
      } else if let result = result {
        let appGuid = KeychainService.loadAppGuid()
        let type = "apns"
        var str = "native.initClient('" + appGuid!
        str += "',  '" + AppName
        str += "', '\(type)', "
        str += "'\(result.token )'"
        str += ", '" + HUBNAME + "')"
        print(str)
        self.webViewController.callJavaScript(command: str)
      }
    }

这是我尝试在 AppDelegate.swift 中接收通知的方式:

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
  let gcmMessageIDKey = "gcm.message_id"
  if let messageID = userInfo[gcmMessageIDKey] {
    print("Message ID: \(messageID)")
  }
  print(userInfo)
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                 fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
  let gcmMessageIDKey = "gcm.message_id"
  if let messageID = userInfo[gcmMessageIDKey] {
    print("Message ID: \(messageID)")
  }
  print(userInfo)
  completionHandler(UIBackgroundFetchResult.newData)
}

但是 none 这些方法被调用了。推送通知证书、标识符和配置文件正确且有效。我 运行 此代码在 Xcode 模拟器上。为什么它不起作用?

您需要一个真实的设备来测试推送通知。