Skip to content

Instantly share code, notes, and snippets.

@janodev
Created August 16, 2016 12:53
Show Gist options
  • Save janodev/160736b47ee9d2a96dfeecb50dc2b97c to your computer and use it in GitHub Desktop.
Save janodev/160736b47ee9d2a96dfeecb50dc2b97c to your computer and use it in GitHub Desktop.
Recover a notification attachment
import UIKit
import UserNotifications
import UserNotificationsUI
struct Attachments {
static let image = (identifier:"image", jsonElement:"imageURL")
}
class ContentViewController: UIViewController, UNNotificationContentExtension
{
@IBOutlet var kittenImage: UIImageView!
func didReceive(_ notification: UNNotification)
{
if let image = imageIn(notification: notification, withIdentifier: Attachments.image.identifier) {
self.kittenImage.image = image
}
}
private func imageIn(notification:UNNotification, withIdentifier: String) -> UIImage?
{
var image: UIImage?
let findImage: (UNNotificationAttachment)->Bool = { attachment in attachment.identifier == Attachments.image.identifier }
if let attachment = notification.request.content.attachments.first(where: findImage) {
if attachment.url.startAccessingSecurityScopedResource() {
image = UIImage(contentsOfFile: attachment.url.path)
attachment.url.stopAccessingSecurityScopedResource()
}
}
return image
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment