如何在iOS 10中设置徽章计数以进行推送



我想在收到通知时设置徽章计数。收到通知时调用below方法。但是徽章计数未设置。

     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 10中,这两种方法称为:

如果应用在前景中:

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

如果应用在后台:

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

您需要获得notificationrequestcontent

  • 前景方法

    let content = notification.request.content
    
  • 背景方法

    let content = response.notification.request.content
    

徽章编号在content的属性badge

let badgeNumber = content.badge as! Int

我缺少徽章的授权。我在代码中添加了徽章

 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

中添加了它

最新更新