Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save barbaramartina/06616dd43abf671b689ca8d10ded9ce2 to your computer and use it in GitHub Desktop.
Save barbaramartina/06616dd43abf671b689ca8d10ded9ce2 to your computer and use it in GitHub Desktop.
Swift 3: implement a service extension and download an image attachment.
//
// NotificationService.swift
// Service
//
// Created by Barbara Rodeker on 28/09/16.
// Copyright © 2016 Barbara Rodeker. All rights reserved.
//
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)
if let bestAttemptContent = bestAttemptContent {
if let urlString = bestAttemptContent.userInfo["picture"] as? String,
let data = NSData(contentsOf: URL(string:urlString)!) as? Data {
let path = NSTemporaryDirectory() + "attachment"
_ = FileManager.default.createFile(atPath: path, contents: data, attributes: nil)
do {
let file = URL(fileURLWithPath: path)
let attachment = try UNNotificationAttachment(identifier: "attachment", url: file,options:[UNNotificationAttachmentOptionsTypeHintKey : "public.jpeg"])
bestAttemptContent.attachments = [attachment]
} catch {
print(error)
}
}
contentHandler(bestAttemptContent)
}
}
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 contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
contentHandler(bestAttemptContent)
}
}
}
// The example is based in a payload like the following:
/*{
"aps":{
"alert":"Do you like puppies?",
"category":"any-name-2",
"mutable-content":1
},
"picture" : "https://pixabay.com/static/uploads/photo/2015/02/05/12/09/chihuahua-624924__180.jpg"
}*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment