2017-10-06 103 views
0

我需要幫助完成這段代碼,以便在收到推送通知時應用會顯示徽章號碼,我可以收到推送通知,但只有應用上沒有徽章,這裏是代碼如何在收到推送通知時更新徽章號碼

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

if let aps = userInfo["aps"] as? NSDictionary, let _ = aps["alert"] as? String, let sound = aps["sound"] as? String 
     { 

      if let systemSound = SystemSoundID(sound) { 
      AudioServicesPlayAlertSound(systemSound) 
     } 

     NotificationCenter.default.post(name: Notification.Name(rawValue: SystemSetting.refreshCouponListNotification), object: nil) 

     completionHandler(UIBackgroundFetchResult.newData) 
    } 
} 
+0

您可以按照本教程https://eladnava.com/send-push-notifications-to-ios-devices-using-xcode-8-and-swift- 3 /和https://stackoverflow.com/questions/44490391/swift-3-turn-off-badge-alert-sound – iPatel

回答

0

有兩種方法被稱爲推送通知

  1. 前景方法
  2. 背景方法

1.地面方法。通知的請求

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

獲取內容

let content = notification.request.content 

2.Background方法

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

得到通知的請求的內容

let content = response.notification.request.content 

獲取徽章計數

let badge = content.badge as! Int 
0

按照以下步驟來設置徽章計數在IOS:

1.Implement邏輯在後端來計算計數,併發送通過推送通知像數:

{ "aps" : { "alert" : "You got your Push Message.", "badge" : 9 } }

2。從推送通知回覆中獲取徽章計數:

let pushContent = response.notification.request.content 
let badgeCount = content.badge as! Int 

3.設置徽章計數didReceiveRemoteNotification方法:

UIApplication.sharedApplication().applicationIconBadgeNumber = badgeCount