ios – 用户通知框架徽章不会增加

前端之家收集整理的这篇文章主要介绍了ios – 用户通知框架徽章不会增加前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在我的应用程序中使用UserNotification框架并发送本地通知(不是推送通知),我想将徽章设置为收到的通知数量,所以我做的是将收到的通知数设置为用户默认值然后我尝试过将值分配给徽章以获取徽章编号,但徽章编号不会增加.这是我的代码

设置接收通知的值

  1. center.getDeliveredNotifications { notification in
  2.  
  3. UserDefaults.standard.set(notification.count,forKey: Constants.NOTIFICATION_COUNT)
  4. print("notification.count \(notification.count)")
  5. print(".count noti \(UserDefaults.standard.integer(forKey: Constants.NOTIFICATION_COUNT))")
  6.  
  7. }

这准确地打印了收到的通知数量,当我决定将其设置为我的徽章时,它只显示1

  1. content.badge = NSNumber(value: UserDefaults.standard.integer(forKey: Constants.NOTIFICATION_COUNT))

我不知道为什么价值不会每次都增加.任何帮助,将不胜感激.

或者,如果可以在应用程序的任何位置始终更新徽章.

解决方法

像这样发送本地通知
  1. func sendNotification(title: String,subtitle: String,body: String,timeInterval: TimeInterval) {
  2. let center = UNUserNotificationCenter.current()
  3. center.getPendingNotificationRequests(completionHandler: { pendingNotificationRequests in
  4.  
  5. //Use the main thread since we want to access UIApplication.shared.applicationIconBadgeNumber
  6. DispatchQueue.main.sync {
  7.  
  8. //Create the new content
  9. let content = UNMutableNotificationContent()
  10. content.title = title
  11. content.subtitle = subtitle
  12. content.body = body
  13.  
  14. //Let's store the firing date of this notification in content.userInfo
  15. let firingDate = Date().timeIntervalSince1970 + timeInterval
  16. content.userInfo = ["timeInterval": firingDate]
  17.  
  18. //get the count of pending notification that will be fired earlier than this one
  19. let earlierNotificationsCount: Int = pendingNotificationRequests.filter { request in
  20.  
  21. let userInfo = request.content.userInfo
  22. if let time = userInfo["timeInterval"] as? Double {
  23. if time < firingDate {
  24. return true
  25. } else {
  26.  
  27. //Here we update the notofication that have been created earlier,BUT have a later firing date
  28. let newContent: UNMutableNotificationContent = request.content.mutableCopy() as! UNMutableNotificationContent
  29. newContent.badge = (Int(truncating: request.content.badge ?? 0) + 1) as NSNumber
  30. let newRequest: UNNotificationRequest =
  31. UNNotificationRequest(identifier: request.identifier,content: newContent,trigger: request.trigger)
  32. center.add(newRequest,withCompletionHandler: { (error) in
  33. // Handle error
  34. })
  35. return false
  36. }
  37. }
  38. return false
  39. }.count
  40.  
  41. //Set the badge
  42. content.badge = NSNumber(integerLiteral: UIApplication.shared.applicationIconBadgeNumber + earlierNotificationsCount + 1)
  43. let trigger = UNTimeIntervalNotificationTrigger(timeInterval: timeInterval,repeats: false)
  44.  
  45. let requestIdentifier = UUID().uuidString //You probably want to save these request identifiers if you want to remove the corresponding notifications later
  46. let request = UNNotificationRequest(identifier: requestIdentifier,content: content,trigger: trigger)
  47.  
  48. center.add(request,withCompletionHandler: { (error) in
  49. // Handle error
  50. })
  51. }
  52. })
  53. }

(您可能需要保存请求的标识符(如果您想更新它们,可以在用户默认值或核心数据中保存,甚至可以通过removePendingNotificationRequests(withIdentifiers:)取消它们)

您可以像这样调用上面的函数

  1. sendNotification(title: "Meeting Reminder",subtitle: "Staff Meeting in 20 minutes",body: "Don't forget to bring coffee.",timeInterval: 10)

将您的视图控制器声明为UNUserNotificationCenterDelegate:

  1. class ViewController: UIViewController,UNUserNotificationCenterDelegate {
  2. override func viewDidLoad() {
  3. super.viewDidLoad()
  4. UNUserNotificationCenter.current().delegate = self
  5. }
  6. //...
  7. }

要处理与通知的互动,请更新应用的徽章以及即将发布的通知的徽章:

  1. func userNotificationCenter(_ center: UNUserNotificationCenter,didReceive response: UNNotificationResponse,withCompletionHandler completionHandler: @escaping () -> Void) {
  2.  
  3. //UI updates are done in the main thread
  4. DispatchQueue.main.async {
  5. UIApplication.shared.applicationIconBadgeNumber -= 1
  6. }
  7.  
  8. let center = UNUserNotificationCenter.current()
  9. center.getPendingNotificationRequests(completionHandler: {requests in
  10. //Update only the notifications that have userInfo["timeInterval"] set
  11. let newRequests: [UNNotificationRequest] =
  12. requests
  13. .filter{ rq in
  14. return rq.content.userInfo["timeInterval"] is Double?
  15. }
  16. .map { request in
  17. let newContent: UNMutableNotificationContent = request.content.mutableCopy() as! UNMutableNotificationContent
  18. newContent.badge = (Int(truncating: request.content.badge ?? 0) - 1) as NSNumber
  19. let newRequest: UNNotificationRequest =
  20. UNNotificationRequest(identifier: request.identifier,trigger: request.trigger)
  21. return newRequest
  22. }
  23. newRequests.forEach { center.add($0,withCompletionHandler: { (error) in
  24. // Handle error
  25. })
  26. }
  27. })
  28. completionHandler()
  29. }

这会在通知与点击进行交互时通过减少应用徽章来更新应用徽章.此外,它还会更新待处理通知内容徽章.添加具有相同标识符的通知请求只会更新待处理通知.

要在前台接收通知,并在未与通知交互时增加应用徽章图标,请执行以下操作:

  1. func userNotificationCenter(_ center: UNUserNotificationCenter,willPresent notification: UNNotification,withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
  2. DispatchQueue.main.async {
  3. UIApplication.shared.applicationIconBadgeNumber += 1
  4. }
  5. completionHandler([.alert,.sound])
  6. }

这是一些GIF:

> 1st:接收本地通知增加应用徽章.而与通知进行交互会减少应用徽章.
> 2nd:应用程序被杀时接收本地通知(我在此使用了15秒的触发timeInterval).
> 3rd:在前台接收通知增加应用程序徽章,除非用户与之交互.

我的测试项目中使用的完整类看起来像这样:

  1. import UIKit
  2. import UserNotifications
  3.  
  4. class ViewController: UIViewController,UNUserNotificationCenterDelegate {
  5. var bit = true
  6. @IBAction func send(_ sender: UIButton) {
  7. let time: TimeInterval = bit ? 8 : 4
  8. bit.toggle()
  9. sendNotification(title: "Meeting Reminder",timeInterval: time)
  10. }
  11.  
  12. override func viewDidLoad() {
  13. super.viewDidLoad()
  14. // Do any additional setup after loading the view,typically from a nib.
  15.  
  16. UNUserNotificationCenter.current().delegate = self
  17. }
  18.  
  19. func sendNotification(title: String,timeInterval: TimeInterval) {
  20. let center = UNUserNotificationCenter.current()
  21. center.getPendingNotificationRequests(completionHandler: { pendingNotificationRequests in
  22. DispatchQueue.main.sync {
  23. let content = UNMutableNotificationContent()
  24. content.title = title
  25. content.subtitle = subtitle
  26. content.body = body
  27. let firingDate = Date().timeIntervalSince1970 + timeInterval
  28. content.userInfo = ["timeInterval": firingDate]
  29. let earlierNotificationsCount: Int = pendingNotificationRequests.filter { request in
  30. let userInfo = request.content.userInfo
  31. if let time = userInfo["timeInterval"] as? Double {
  32. if time < firingDate {
  33. return true
  34. } else {
  35. let newContent: UNMutableNotificationContent = request.content.mutableCopy() as! UNMutableNotificationContent
  36. newContent.badge = (Int(truncating: request.content.badge ?? 0) + 1) as NSNumber
  37. let newRequest: UNNotificationRequest =
  38. UNNotificationRequest(identifier: request.identifier,trigger: request.trigger)
  39. center.add(newRequest,withCompletionHandler: { (error) in
  40. // Handle error
  41. })
  42. return false
  43. }
  44. }
  45. return false
  46. }.count
  47. content.badge = NSNumber(integerLiteral: UIApplication.shared.applicationIconBadgeNumber + earlierNotificationsCount + 1)
  48. let trigger = UNTimeIntervalNotificationTrigger(timeInterval: timeInterval,repeats: false)
  49.  
  50. let requestIdentifier = UUID().uuidString //You probably want to save these request identifiers if you want to remove the corresponding notifications later
  51. let request = UNNotificationRequest(identifier: requestIdentifier,trigger: trigger)
  52.  
  53. center.add(request,withCompletionHandler: { (error) in
  54. // Handle error
  55. })
  56. }
  57. })
  58. }
  59.  
  60. func userNotificationCenter(_ center: UNUserNotificationCenter,withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
  61. DispatchQueue.main.async {
  62. UIApplication.shared.applicationIconBadgeNumber += 1
  63. }
  64. completionHandler([.alert,.sound])
  65. }
  66.  
  67. func userNotificationCenter(_ center: UNUserNotificationCenter,withCompletionHandler completionHandler: @escaping () -> Void) {
  68. DispatchQueue.main.async {
  69. UIApplication.shared.applicationIconBadgeNumber -= 1
  70. }
  71.  
  72. let center = UNUserNotificationCenter.current()
  73. center.getPendingNotificationRequests(completionHandler: {requests in
  74. let newRequests: [UNNotificationRequest] =
  75. requests
  76. .filter{ rq in
  77. return rq.content.userInfo["timeInterval"] is Double?
  78. }
  79. .map { request in
  80. let newContent: UNMutableNotificationContent = request.content.mutableCopy() as! UNMutableNotificationContent
  81. newContent.badge = (Int(truncating: request.content.badge ?? 0) - 1) as NSNumber
  82. let newRequest: UNNotificationRequest =
  83. UNNotificationRequest(identifier: request.identifier,trigger: request.trigger)
  84. return newRequest
  85. }
  86. newRequests.forEach { center.add($0,withCompletionHandler: { (error) in
  87. // Handle error
  88. })
  89. }
  90. })
  91. completionHandler()
  92. }
  93. }

猜你在找的iOS相关文章