Skip to content

Instantly share code, notes, and snippets.

@3257
Last active November 30, 2020 15:37
Show Gist options
  • Save 3257/fd3b4ff90f6eba48ab4b947e5a5bff69 to your computer and use it in GitHub Desktop.
Save 3257/fd3b4ff90f6eba48ab4b947e5a5bff69 to your computer and use it in GitHub Desktop.
// MARK: - Helper Functions
extension NotificationService {
/// Use this function to download an image and present it in a notification
///
/// - Parameters:
/// - url: the url of the picture
/// - completion: return the image in the form of UNNotificationAttachment to be added to the bestAttemptContent attachments eventually
private func downloadImageFrom(url: URL, with completionHandler: @escaping (UNNotificationAttachment?) -> Void) {
let task = URLSession.shared.downloadTask(with: url) { (downloadedUrl, response, error) in
// 1. Test URL and escape if URL not OK
guard let downloadedUrl = downloadedUrl else {
completionHandler(nil)
return
}
// 2. Get current's user temporary directory path
var urlPath = URL(fileURLWithPath: NSTemporaryDirectory())
// 3. Add proper ending to url path, in the case .jpg (The system validates the content of attached files before scheduling the corresponding notification request. If an attached file is corrupted, invalid, or of an unsupported file type, the notification request is not scheduled for delivery. )
let uniqueURLEnding = ProcessInfo.processInfo.globallyUniqueString + ".jpg"
urlPath = urlPath.appendingPathComponent(uniqueURLEnding)
// 4. Move downloadedUrl to newly created urlPath
try? FileManager.default.moveItem(at: downloadedUrl, to: urlPath)
// 5. Try adding getting the attachment and pass it to the completion handler
do {
let attachment = try UNNotificationAttachment(identifier: "picture", url: urlPath, options: nil)
completionHandler(attachment)
}
catch {
completionHandler(nil)
}
}
task.resume()
}
@jriosdev
Copy link

after step 4. Move downloadedUrl to newly created urlPath
try? FileManager.default.moveItem(at: downloadedUrl, to: urlPath)

this file moved to a new path
after push notification seen, do I need to remove content from that new file location

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment