问题
I need help finishing this piece of code so the app will show badge number when a push notification is received, I can receive push notification, but just no badge on app, here is the code
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)
}
}
回答1:
There is the two Methods are Called for Push notification
- Foreground Method
- Background Method
1.Foreground Method.
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
Get content of Request of Notification
let content = notification.request.content
2.Background Method
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void)
Get content of Request of Notification
let content = response.notification.request.content
Get Badge Count
let badge = content.badge as! Int
回答2:
Follow these steps to set badge count in iOS :
1.Implement logic to calculate count in backend and send that count through Push notification like :
{
"aps" : {
"alert" : "You got your Push Message.",
"badge" : 9
}
}
2.Get Badge count from Push notification response :
let pushContent = response.notification.request.content
let badgeCount = content.badge as! Int
3.set badge count in didReceiveRemoteNotification method :
UIApplication.sharedApplication().applicationIconBadgeNumber = badgeCount
来源:https://stackoverflow.com/questions/46598362/how-to-update-badge-number-when-receive-push-notification