【问题标题】:iOS 10.0 * Handle Push notification in foregroundiOS 10.0 * 在前台处理推送通知
【发布时间】:2017-07-13 09:10:49
【问题描述】:

如果我在 ios 10.0 中实现推送通知的方法

@available(iOS 10.0, *)

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

    }

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

【问题讨论】:

标签: ios swift3 push-notification notifications apple-push-notifications


【解决方案1】:

我的推送数据是

{
    "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)


    }

【讨论】:

    【解决方案2】:

    根据官方文档:

    // 仅当应用程序在委托上调用该方法 在前台。如果方法未实现或处理程序 没有及时调用,则不会通知 呈现。应用程序可以选择接收通知 以声音、徽章、警报和/或通知列表的形式呈现。 该决定应基于 否则通知对用户可见。

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

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

    希望对你有帮助。

    【讨论】:

    • 我的问题是关于应用程序何时处于前台,我想阻止特定通知而不是全部
    • 在这种情况下,您可以检查通知负载,如果您想隐藏特定通知,请不要调用处理程序。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-26
    • 2020-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-27
    • 2017-06-26
    相关资源
    最近更新 更多