Skip to content

Instantly share code, notes, and snippets.

@UtkuGlsvn
Created January 30, 2021 09:23
Show Gist options
  • Save UtkuGlsvn/273d56c55cd7aeb2c4a8f20fa4a3159d to your computer and use it in GitHub Desktop.
Save UtkuGlsvn/273d56c55cd7aeb2c4a8f20fa4a3159d to your computer and use it in GitHub Desktop.
import UserNotifications
class NotificationService: UNNotificationServiceExtension {
var contentHandler: ((UNNotificationContent) -> Void)?
var bestAttemptContent: UNMutableNotificationContent?
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
self.contentHandler = contentHandler
bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
guard
let content = (request.content.mutableCopy() as? UNMutableNotificationContent),
let apnsData = content.userInfo["data"] as? [String: Any],
let attachmentURL = apnsData["imageurl"] as? String,
let imageData = NSData(contentsOf: NSURL(string: attachmentURL)! as URL),
let attachment = UNNotificationAttachment.create(imageFileIdentifier: "image.png", data: imageData, options: nil)
else {
contentHandler(request.content)
return
}
if #available(iOS 11.0, *) {
let contentAddedCategory = UNNotificationCategory(identifier: "rich-push",
actions: [],
intentIdentifiers: [],
hiddenPreviewsBodyPlaceholder: "",
options: .customDismissAction)
UNUserNotificationCenter.current().setNotificationCategories([contentAddedCategory])
}
content.attachments = [attachment]
contentHandler(content.copy() as! UNNotificationContent)
}
override func serviceExtensionTimeWillExpire() {
// Called just before the extension will be terminated by the system.
// Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
if let bestAttemptContent = bestAttemptContent {
contentHandler?(bestAttemptContent)
}
}
}
// MARK: - UNNotificationAttachment + FileManager
extension UNNotificationAttachment {
static func create(imageFileIdentifier: String, data: NSData, options: [NSObject : AnyObject]?) -> UNNotificationAttachment? {
let fileManager: FileManager = .default
let tmpSubFolderName = ProcessInfo.processInfo.globallyUniqueString
let fileURLPath = NSURL(fileURLWithPath: NSTemporaryDirectory())
let tmpSubFolderURL = fileURLPath.appendingPathComponent(tmpSubFolderName, isDirectory: true)
do {
try fileManager.createDirectory(at: tmpSubFolderURL!, withIntermediateDirectories: true, attributes: nil)
let fileURL = tmpSubFolderURL?.appendingPathComponent(imageFileIdentifier)
try data.write(to: fileURL!, options: [])
let imageAttachment = try UNNotificationAttachment.init(identifier: imageFileIdentifier, url: fileURL!, options: options)
return imageAttachment
}
catch {
print("error \(error)")
}
return nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment