Rich Notifications
To implement rich notifications you will have to create a new Notification Service Target that will be responsible for downloading the media of the notification and attach it to the notification object.
In Xcode go to File -> New -> Target and choose Notification Service Extension
Keep in mind that notifications don't have much time to download the media attached, if the download doesn't finish in a short period of time the notification will be delivered without the media.
To handle MPush attachments add this your NotificationService should look like this:
1
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
2
self.contentHandler = contentHandler
3
bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
4
​
5
if let bestAttemptContent = bestAttemptContent {
6
if let mediaUrl = request.content.userInfo["media_url"] as? String, let fileUrl = URL(string: mediaUrl) {
7
downloadMedia(fileUrl: fileUrl, request: request, bestAttemptContent: bestAttemptContent) {
8
contentHandler(bestAttemptContent)
9
}
10
} else {
11
contentHandler(bestAttemptContent)
12
}
13
}
14
}
15
​
16
func downloadMedia(fileUrl: URL, request: UNNotificationRequest, bestAttemptContent: UNMutableNotificationContent, completion: @escaping () -> Void) {
17
let task = URLSession.shared.downloadTask(with: fileUrl) { (location, _, _) in
18
if let location = location {
19
let tmpDirectory = NSTemporaryDirectory()
20
let tmpFile = "file://".appending(tmpDirectory).appending(fileUrl.lastPathComponent)
21
let tmpUrl = URL(string: tmpFile)!
22
do {
23
try FileManager.default.moveItem(at: location, to: tmpUrl)
24
​
25
var options: [String: String]? = nil
26
if let type = request.content.userInfo["media_type"] as? String {
27
options = [String: String]()
28
options?[UNNotificationAttachmentOptionsTypeHintKey] = type
29
}
30
if let attachment = try? UNNotificationAttachment(identifier: "media." + fileUrl.pathExtension, url: tmpUrl, options: options) {
31
bestAttemptContent.attachments = [attachment]
32
}
33
completion()
34
} catch {
35
completion()
36
}
37
}
38
}
39
task.resume()
40
}
41
​
42
override func serviceExtensionTimeWillExpire() {
43
// Called just before the extension will be terminated by the system.
44
// Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
45
if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
46
contentHandler(bestAttemptContent)
47
}
48
}
Copied!
With this code, we download the attachment, if exists, and move it to a temporary directory. Then we add it to our notification with
1
if let attachment = try? UNNotificationAttachment(identifier: "media." + fileUrl.pathExtension, url: tmpUrl, options: options) {
2
bestAttemptContent.attachments = [attachment]
3
}
Copied!
Last modified 1yr ago
Copy link