NotificationService.swift 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. import UserNotifications
  2. import CoreData
  3. /// This app extension is responsible for persisting the incoming notification to the data store (Core Data). It will eventually be the entity that
  4. /// fetches notification content from selfhosted servers (when a "poll request" is received). This is not implemented yet.
  5. ///
  6. /// Note that the app extension does not run as part of the main app, so log messages are not printed in the main Xcode window. To debug,
  7. /// select Debug -> Attach to Process by PID or Name, and select the extension. Don't forget to set a breakpoint, or you're not gonna have a good time.
  8. class NotificationService: UNNotificationServiceExtension {
  9. private let tag = "NotificationService"
  10. private let actionsCategory = "ntfyActions" // It seems ok to re-use the same category
  11. var contentHandler: ((UNNotificationContent) -> Void)?
  12. var bestAttemptContent: UNMutableNotificationContent?
  13. override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
  14. self.contentHandler = contentHandler
  15. self.bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
  16. Log.d(tag, "Notification received (in service)") // Logs from extensions are not printed in Xcode!
  17. if let bestAttemptContent = bestAttemptContent {
  18. let userInfo = bestAttemptContent.userInfo
  19. // Get all the things
  20. let topic = userInfo["topic"] as? String ?? ""
  21. let title = userInfo["title"] as? String
  22. let priority = userInfo["priority"] as? String ?? "3"
  23. let tags = userInfo["tags"] as? String
  24. let actions = userInfo["actions"] as? String ?? "[]"
  25. // Set notification title to short URL if there is no title. The title is always set
  26. // by the server, but it may be empty.
  27. if let title = title, title == "" {
  28. bestAttemptContent.title = topicShortUrl(baseUrl: Config.appBaseUrl, topic: topic)
  29. }
  30. // Emojify title or message
  31. let emojiTags = parseEmojiTags(tags)
  32. if !emojiTags.isEmpty {
  33. if let title = title, title != "" {
  34. bestAttemptContent.title = emojiTags.joined(separator: "") + " " + bestAttemptContent.title
  35. } else {
  36. bestAttemptContent.body = emojiTags.joined(separator: "") + " " + bestAttemptContent.body
  37. }
  38. }
  39. // Add custom actions
  40. //
  41. // We re-define the categories every time here, which is weird, but it works. When tapped, the action sets the
  42. // actionIdentifier in the application(didReceive) callback. This logic is handled in the AppDelegate. This approach
  43. // is described in a comment in https://stackoverflow.com/questions/30103867/changing-action-titles-in-interactive-notifications-at-run-time#comment122812568_30107065
  44. //
  45. // We also must set the .foreground flag, which brings the notification to the foreground and avoids an error about
  46. // permissions. This is described in https://stackoverflow.com/a/44580916/1440785
  47. if let actions = Actions.shared.parse(actions), !actions.isEmpty {
  48. bestAttemptContent.categoryIdentifier = actionsCategory
  49. let center = UNUserNotificationCenter.current()
  50. let notificationActions = actions.map { UNNotificationAction(identifier: $0.id, title: $0.label, options: [.foreground]) } //
  51. let category = UNNotificationCategory(identifier: actionsCategory, actions: notificationActions, intentIdentifiers: [])
  52. center.setNotificationCategories([category])
  53. }
  54. // Play a sound, and group by topic
  55. bestAttemptContent.sound = .default
  56. bestAttemptContent.threadIdentifier = topic
  57. // Map priorities to interruption level (light up screen, ...) and relevance (order)
  58. if #available(iOS 15.0, *) {
  59. switch priority {
  60. case "1":
  61. bestAttemptContent.interruptionLevel = .passive
  62. bestAttemptContent.relevanceScore = 0
  63. case "2":
  64. bestAttemptContent.interruptionLevel = .passive
  65. bestAttemptContent.relevanceScore = 0.25
  66. case "4":
  67. bestAttemptContent.interruptionLevel = .timeSensitive
  68. bestAttemptContent.relevanceScore = 0.75
  69. case "5":
  70. bestAttemptContent.interruptionLevel = .critical
  71. bestAttemptContent.relevanceScore = 1
  72. default:
  73. bestAttemptContent.interruptionLevel = .active
  74. bestAttemptContent.relevanceScore = 0.5
  75. }
  76. }
  77. // Save notification to store, and display it
  78. Store.shared.save(notificationFromUserInfo: userInfo)
  79. contentHandler(bestAttemptContent)
  80. }
  81. }
  82. override func serviceExtensionTimeWillExpire() {
  83. // Called just before the extension will be terminated by the system.
  84. // Use this as an opportunity to deliver your "best attempt" at modified content,
  85. // otherwise the original push payload will be used.
  86. if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
  87. contentHandler(bestAttemptContent)
  88. }
  89. }
  90. }