在应用程序中,Swift确实接收了远程通知

时间:2017-08-25 20:22:30

标签: ios swift swift3 push-notification notifications

以下是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)
    }
}

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

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

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

提前致谢!

2 个答案:

答案 0 :(得分:3)

将您的代码包装在:

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

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

答案 1 :(得分: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
}