NotificationService.swift 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. //
  2. // NotificationService.swift
  3. // O2PlatformExtPushStatistics
  4. //
  5. // Created by 刘振兴 on 2018/4/14.
  6. // Copyright © 2018年 zoneland. All rights reserved.
  7. //
  8. import UserNotifications
  9. @available(iOSApplicationExtension 10.0, *)
  10. class NotificationService: UNNotificationServiceExtension {
  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. bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
  16. if let bestAttemptContent = bestAttemptContent {
  17. // Modify the notification content here...
  18. bestAttemptContent.title = "\(bestAttemptContent.title) [modified]"
  19. let session = URLSession.shared
  20. let attachmentPath = self.bestAttemptContent?.userInfo["my-attachment"]
  21. if let attachPath = attachmentPath,(attachPath as AnyObject).hasSuffix("png") {
  22. let task = session.dataTask(with: URL.init(string: attachPath as! String)!) { (data, response, error) in
  23. if let _ = data {
  24. let localPath = "\(NSTemporaryDirectory())/myAttachment.png"
  25. if NSData(data: data!).write(toFile: localPath, atomically: true) {
  26. let attachment = try! UNNotificationAttachment(identifier: "myAttachment", url: URL(fileURLWithPath: localPath), options: nil)
  27. self.bestAttemptContent?.attachments = [attachment]
  28. }
  29. }
  30. self.apnsDeliver(request: request)
  31. }
  32. task.resume()
  33. }else{
  34. self.apnsDeliver(request: request)
  35. }
  36. //contentHandler(bestAttemptContent)
  37. }
  38. }
  39. func apnsDeliver(request:UNNotificationRequest){
  40. JPushNotificationExtensionService.jpushSetAppkey("")
  41. JPushNotificationExtensionService.jpushReceive(request) {
  42. print("apns upload success")
  43. if let contentHandler = self.contentHandler, let bestAttemptContent = self.bestAttemptContent {
  44. contentHandler(bestAttemptContent)
  45. }
  46. }
  47. }
  48. override func serviceExtensionTimeWillExpire() {
  49. // Called just before the extension will be terminated by the system.
  50. // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
  51. if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
  52. contentHandler(bestAttemptContent)
  53. }
  54. }
  55. }