Rich Notifications
From MBurger you can send medias (images/videos/audio) with a push notification. The link of the media will be sent in the payload of the notifications in the media_url field. To view the media sent in the notifications follow tihs steps, as described in the MPush documentation.

1. Create a Notification Service target

In Xcode go to File -> New Target and choose Notification Service Extension​
. This will create a class that will intercept all push notification sent to the app, you will be able to change its content from this class.

2. Download the media

In the notification service class use this code to download the media and attach to the push notification.
1
class NotificationService: UNNotificationServiceExtension {
2
​
3
var contentHandler: ((UNNotificationContent) -> Void)?
4
var bestAttemptContent: UNMutableNotificationContent?
5
​
6
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
7
self.contentHandler = contentHandler
8
bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
9
10
if let bestAttemptContent = bestAttemptContent {
11
if let mediaUrl = request.content.userInfo["media_url"] as? String, let fileUrl = URL(string: mediaUrl) {
12
let type = request.content.userInfo["media_type"] as? String
13
downloadMedia(fileUrl: fileUrl, type: type, request: request, bestAttemptContent: bestAttemptContent) {
14
contentHandler(bestAttemptContent)
15
}
16
} else {
17
contentHandler(bestAttemptContent)
18
}
19
}
20
}
21
22
func downloadMedia(fileUrl: URL, type: String?, request: UNNotificationRequest, bestAttemptContent: UNMutableNotificationContent, completion: @escaping () -> Void) {
23
let task = URLSession.shared.downloadTask(with: fileUrl) { (location, _, _) in
24
if let location = location {
25
let tmpDirectory = NSTemporaryDirectory()
26
let tmpFile = "file://".appending(tmpDirectory).appending(fileUrl.lastPathComponent)
27
let tmpUrl = URL(string: tmpFile)!
28
do {
29
try FileManager.default.moveItem(at: location, to: tmpUrl)
30
31
var options: [String: String]? = nil
32
if let type = type {
33
options = [String: String]()
34
options?[UNNotificationAttachmentOptionsTypeHintKey] = type
35
}
36
if let attachment = try? UNNotificationAttachment(identifier: "media." + fileUrl.pathExtension, url: tmpUrl, options: options) {
37
bestAttemptContent.attachments = [attachment]
38
}
39
completion()
40
} catch {
41
completion()
42
}
43
}
44
}
45
task.resume()
46
}
47
​
48
override func serviceExtensionTimeWillExpire() {
49
if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
50
contentHandler(bestAttemptContent)
51
}
52
}
53
}
Copied!
Last modified 11mo ago