【问题标题】:Why does push notification ios work after rebooting the device?为什么推送通知ios在重启设备后会起作用?
【发布时间】:2020-04-25 09:24:27
【问题描述】:

我正在尝试通过 FCM(Firebase 云消息传递)实现推送通知。现在,我使用Messaging.messaging().subscribe 进行后台推送通知。 但是不知何故,推送通知会在一分钟内起作用,而在一段时间后它就不能完全起作用。然后,当我重新启动设备时,推送通知再次开始工作。会有什么问题??

这是 AppDelegate 中的基本设置

import UIKit
import UserNotifications
import Firebase

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

  let gcmMessageIDKey = "gcm.message_id"

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    FirebaseApp.configure()
    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
//    Messaging.messaging().unsubscribe(fromTopic: "dev_store_abcde-acbcd-adbcd-bcddd") { error in
//      print("unsub")
//    }
    application.registerForRemoteNotifications()
    return true
  }

  func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    let deviceTokenString = deviceToken.hexString
    print(deviceTokenString)
    InstanceID.instanceID().instanceID { (result, error) in
      if let error = error {
        print("Error fetching remote instance ID: \(error)")
      } else if let result = result {
        print("Remote instance ID token: \(result.token)")
      }
    }
  }
  // MARK: UISceneSession Lifecycle

  func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
    // Called when a new scene session is being created.
    // Use this method to select a configuration to create the new scene with.
    return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
  }

  func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
    // Called when the user discards a scene session.
    // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
    // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
  }
}
extension AppDelegate: MessagingDelegate {
  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)
    Messaging.messaging().subscribe(toTopic: "dev_store_id") { error in
      print("Subscribe to dev_store_id")
    }
    // 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("Message Data", remoteMessage.appData)
  }
}

@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {
  func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    print(userInfo["value"])
    UserDefaults.standard.set(true, forKey: "isNotified")
    UserDefaults.standard.synchronize()
    completionHandler(.newData)
  }
}

extension Data {
  var hexString: String {
    let hexString = map { String(format: "%02.2hhx", $0) }.joined()
    return hexString
  }
}



【问题讨论】:

    标签: ios swift firebase push-notification firebase-cloud-messaging


    【解决方案1】:

    打开/关闭 wifi 后发现似乎适用于开发版本。如果将通知部署到分发版本中,静默通知的效果会非常好。

    【讨论】:

      猜你喜欢
      • 2020-02-19
      • 1970-01-01
      • 2016-03-22
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 2020-08-22
      • 2021-04-06
      • 1970-01-01
      相关资源
      最近更新 更多