Created
September 14, 2016 17:45
-
-
Save suraphanL/742f8d9fd00528fe634b95ffb639a0b0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) { | |
func failEarly() { | |
print("fail") | |
contentHandler(request.content) | |
} | |
guard let content = (request.content.mutableCopy() as? UNMutableNotificationContent) else { | |
return failEarly() | |
} | |
guard let attachmentURL = content.userInfo["attachement-url"] as? String else { | |
return failEarly() | |
} | |
do { | |
let imageData = try Data(contentsOf: URL(string: attachmentURL)!) | |
guard let attachment = UNNotificationAttachment.create(imageFileIdentifier: "image.png", data: imageData, options: nil) else { return failEarly() } | |
content.attachments = [attachment] | |
contentHandler(content.copy() as! UNNotificationContent) | |
} catch { | |
} | |
} | |
extension UNNotificationAttachment { | |
/// Save the image to disk | |
static func create(imageFileIdentifier: String, data: Data, options: [NSObject : AnyObject]?) -> UNNotificationAttachment? { | |
let fileManager = FileManager.default | |
let tmpSubFolderName = ProcessInfo.processInfo.globallyUniqueString | |
let tmpSubFolderURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(tmpSubFolderName, isDirectory: true) | |
do { | |
try fileManager.createDirectory(at: tmpSubFolderURL, withIntermediateDirectories: true, attributes: nil) | |
let fileURL = tmpSubFolderURL.appendingPathComponent(imageFileIdentifier) | |
try data.write(to: fileURL) | |
let imageAttachment = try UNNotificationAttachment.init(identifier: imageFileIdentifier, url: fileURL, options: options) | |
return imageAttachment | |
} catch let error { | |
print(error) | |
} | |
return nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment