【问题标题】:How to set badge count in iOS 10 for pushnotification?如何在 iOS 10 中为推送通知设置徽章计数?
【发布时间】:2016-12-12 14:28:31
【问题描述】:

我想在收到通知时在应用程序图标上设置徽章计数。收到通知时调用以下方法。但未设置徽章计数。

     func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

        var userData = userInfo as NSDictionary? as? [AnyHashable: Any] ?? [:]
        var aps  = userData["aps"] as! NSDictionary
        var badge = aps["badge"]
        print("data is \(badge!)")
        UIApplication.shared.applicationIconBadgeNumber = badge! as! Int
        if #available(iOS 10.0, *) {
          let content = UNMutableNotificationContent()
          content.badge = 10
        } else {
          // Fallback on earlier versions
        }
        // your badge count
}

【问题讨论】:

    标签: ios swift push-notification appdelegate


    【解决方案1】:

    实际上在 iOS 10 中这两个方法被调用:

    如果应用在前台:

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

    如果应用在后台:

       func userNotificationCenter(_ center: UNUserNotificationCenter, 
                        didReceive response: UNNotificationResponse, 
    withCompletionHandler completionHandler: @escaping () -> Void)
    

    你需要得到content的request的notification的content

    • 前台方法

      let content = notification.request.content
      
    • 后台方法

      let content = response.notification.request.content
      

    徽章编号在content 的属性badge 中

    let badgeNumber = content.badge as! Int
    

    【讨论】:

    • @Kiranjadhav 请停止在您能找到的任何相关线程上发布此评论。它无法在 cmets 中得到充分回答,而且您正在 ping 很多用户,这可能很烦人。请改为提出新问题。
    • @vadian,,,我从几天开始尝试,但我没有得到适当的解决方案,如果可能的话,请尝试向我解释其他明智的问题,谢谢......!
    • 这两个都没有被调用。
    【解决方案2】:

    我错过了徽章的授权。我在代码中添加了徽章

     if #available(iOS 10.0, *) {
          let center = UNUserNotificationCenter.current()
          center.requestAuthorization(options: [.alert, .sound,.badge]) { (granted, error) in
            // actions based on whether notifications were authorized or not
          }
          application.registerForRemoteNotifications()
        }
    

    我在didFinishLaunchWithOptions添加了这个

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-07
      • 1970-01-01
      • 1970-01-01
      • 2017-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-23
      相关资源
      最近更新 更多