为啥推送通知ios在重启设备后会起作用?

Posted

技术标签:

【中文标题】为啥推送通知ios在重启设备后会起作用?【英文标题】: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
  




【问题讨论】:

【参考方案1】:

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

【讨论】:

以上是关于为啥推送通知ios在重启设备后会起作用?的主要内容,如果未能解决你的问题,请参考以下文章

如果用户关闭应用程序的通知,静默推送通知会起作用吗?

为啥推送通知不能在 iOS 中使用 Firebase 从设备到设备?

如果用户既没有允许也没有“不允许”我的应用程序的推送通知,推送通知会起作用吗?

为啥远程推送通知在 iOS 10 上不起作用?

2195端口是强制要求开放的吗? IOS 推送通知在 php 中不起作用,而 Ios 推送通知在 laravel 中没有进入移动设备

为啥没有通过 Firebase FCM 从 Web API 定向到特定 iOS 设备的推送通知?