NotificationService.swift 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import UserNotifications
  2. import OneSignal
  3. class NotificationService: UNNotificationServiceExtension {
  4. var contentHandler: ((UNNotificationContent) -> Void)?
  5. var receivedRequest: UNNotificationRequest!
  6. var bestAttemptContent: UNMutableNotificationContent?
  7. override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
  8. self.receivedRequest = request
  9. self.contentHandler = contentHandler
  10. self.bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
  11. if let bestAttemptContent = bestAttemptContent {
  12. //If your SDK version is < 3.5.0 uncomment and use this code:
  13. /*
  14. OneSignal.didReceiveNotificationExtensionRequest(self.receivedRequest, with: self.bestAttemptContent)
  15. contentHandler(bestAttemptContent)
  16. */
  17. /* DEBUGGING: Uncomment the 2 lines below to check this extension is excuting
  18. Note, this extension only runs when mutable-content is set
  19. Setting an attachment or action buttons automatically adds this */
  20. //OneSignal.setLogLevel(.LL_VERBOSE, visualLevel: .LL_NONE)
  21. //bestAttemptContent.body = "[Modified] " + bestAttemptContent.body
  22. OneSignal.didReceiveNotificationExtensionRequest(self.receivedRequest, with: bestAttemptContent, withContentHandler: self.contentHandler)
  23. }
  24. }
  25. override func serviceExtensionTimeWillExpire() {
  26. // Called just before the extension will be terminated by the system.
  27. // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
  28. if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
  29. OneSignal.serviceExtensionTimeWillExpireRequest(self.receivedRequest, with: self.bestAttemptContent)
  30. contentHandler(bestAttemptContent)
  31. }
  32. }
  33. }