iOS 10.0 * 在前台处理推送通知

iOS 10.0 * Handle Push notification in foreground

如果我在 ios 10.0

中实现呈现推送通知的方法
@available(iOS 10.0, *)

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
    {
        completionHandler(UNNotificationPresentationOptions.alert)

    }

然后显示所有通知, 所以,我的问题是如何防止显示特定的推送通知,例如(在另一个设备上登录)我只处理该特定推送的代码

根据官方文档:

// The method will be called on the delegate only if the application is in the foreground. If the method is not implemented or the handler is not called in a timely manner then the notification will not be presented. The application can choose to have the notification presented as a sound, badge, alert and/or in the notification list. This decision should be based on whether the information in the notification is otherwise visible to the user.

- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);

所以回答你的问题,如果你想阻止显示通知,要么不实现这个方法,要么不调用处理程序。

希望对您有所帮助。

我的推送数据是

{
    "aps" : {
        "alert" : {
            "id" : 2091
        },
        "sound" : "chime.aiff"
    },
    "acme" : "foo"
}

我使用了 id,因为我可以通过它的 id 来分隔每个推送,并且基于 id 我可以决定天气是否在前台显示通知..

感谢@Anbu.Karthik 供参考 根据我的问题,即使用户没有点击

中的通知,我们也可以处理推送
   @available(iOS 10.0, *)

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
    {
        print("Handle push from foreground")
        let userInfo:[AnyHashable:Any] =  notification.request.content.userInfo
        let aps:NSDictionary = (userInfo[AnyHashable("aps")] as? NSDictionary)!
        let alert:NSDictionary = (aps["alert"] as? NSDictionary)!
        let id = Int(alert["id"] as! Int)
        if id == your id
        {    
         //Handle push without prompting alert 
        }

        else
        {
          //Display alert
         completionHandler(UNNotificationPresentationOptions.alert)
        }
    }

并且当用户点击通知时调用以下方法...

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {

        print(userInfo)


    }