【问题标题】:Swift didReceiveRemoteNotification firing while in appSwift didReceiveRemoteNotification 在应用程序中触发
【发布时间】:2017-08-25 20:22:30
【问题描述】:

这是我的didReceiveRemoteNotification 代码:

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
    print("notification recieved: \(userInfo)")

    // Pass push notification payload to the shared model
    let payload: NSDictionary = userInfo as NSDictionary

    if let variable = payload["variable"] as? String {
        NotificationManager.SharedInstance.handleVariableNotification(variable)
    }
}

当我从应用程序外部单击通知时,代码可以正常工作并正确执行我想要的操作。

我的问题是:如果我在当前处于应用程序中时收到通知,它仍会运行通知中的代码并覆盖用户当前在应用程序中执行的任何操作

我只希望代码在用户点击通知时运行,而不是在我已经在应用程序中时自动运行。

提前致谢!

【问题讨论】:

    标签: ios swift swift3 push-notification notifications


    【解决方案1】:

    将您的代码包装在:

    if (application.applicationState != .active){}
    

    它将检查您当前是否在应用中,并且仅在应用处于非活动状态或在后台时触发代码。

    【讨论】:

      【解决方案2】:

      在您的 didReceiveRemoteNotification 委托方法中:

      func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
      
          switch application.applicationState {
          case .active:
              print("Application is open, do not override")
          case .inactive, .background:
      
              // Pass push notification payload to the shared model
              let payload: NSDictionary = userInfo as NSDictionary
      
              if let variable = payload["variable"] as? String {
                  NotificationManager.SharedInstance.handleVariableNotification(variable)
              }
      
          default:
              print("unrecognized application state")
          }
      
      }
      

      此外,如果您的应用程序是通过用户打开应用程序发送的远程通知启动,您将需要在应用程序委托didFinishLaunchingWithOptions 方法中执行此操作:

      func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
      
          // Check to see if launchOptions contains any data
          if launchOptions != nil {
      
              // Check to see if the data inside launchOptions is a remote notification
              if let remoteNotification = launchOptions![UIApplicationLaunchOptionsKey.remoteNotification] as? NSDictionary {
      
                  // Do something with the notification
              }
          }
      
          return true
      }
      

      【讨论】:

        猜你喜欢
        • 2018-03-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-15
        相关资源
        最近更新 更多