Ios Service And Content Template For Receiving Rich Push Notifications

Unlike android, IOS requires some tweaking to get rich IOS push notification when dealing with the Firebase messaging package.

Create a notification service target within your application.

File > New > Target > Notification Service Extension

Create a notification content template

File > New > Target > Notification Content Extension

Notification Service Extension

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
//swift
//  NotificationService.swift
//  FirebaseMessagingExt
//
//  Created by Ojong Obasi on 2020/10/10.
//  Copyright © 2020 The Chromium Authors. 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 {
            // Modify the notification content here...
            bestAttemptContent.title = "\(bestAttemptContent.title) [modified]"

            contentHandler(bestAttemptContent)
        }*/
        guard let bestAttemptContent = bestAttemptContent, // 1. Make sure bestAttemptcontent is not nill
            let attachmentURLAsString = bestAttemptContent.userInfo["url"] as? String, // 2. The attachment-url
            let attachmentURL = URL(string: attachmentURLAsString) else { // 3. And parse it to URL.
                return
        }

        // 4. Download the image and pass it to attachments if not nill
        downloadImageFrom(url: attachmentURL){ (attachment) in 
            if let attachment = attachment {
                bestAttemptContent.attachments = [attachment]
                contentHandler(bestAttemptContent)
            }

        }

        // Added Content
    }

    private func downloadImageFrom(url: URL, with completionHandler: @escaping (UNNotificationAttachment?) -> Void) {
        let task = URLSession.shared.downloadTask(with: url) { (downloadUrl, response, error) in
            //1. Test URL and escape if URL not ok
            guard let downloadUrl = downloadUrl 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 of attached files before scheduling the corresponding notification request. If an attached file is corrupted, invalid, or unsupported file type, the notification request is not scheduled for delivery. )
            let uniqueURLEnding = ProcessInfo.processInfo.globallyUniqueString + ".jpg"
            urlPath = urlPath.appendingPathComponent(uniqueURLEnding)

            // 4. Move downloadUrl to newly created urlPath
            try? FileManager.default.moveItem(at: downloadUrl, 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()
    }
}

And the Notification content extension:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
//  NotificationViewController.swift
//  NotificationViewController
//
//  Created by Ojong Obasi on 2020/10/11.
//  Copyright © 2020 The Chromium Authors. All rights reserved.
//

import UIKit
import UserNotifications
import UserNotificationsUI

class NotificationViewController: UIViewController, UNNotificationContentExtension {

    @IBOutlet var label: UILabel?
    @IBOutlet var imageVw: UIImageView?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any required interface initialization here.
    }

    func didReceive(_ notification: UNNotification) {
        self.label?.text = notification.request.content.body
        let attachments = notification.request.content.attachments
        for attachment in attachments {
            if attachment.identifier == "picture" {
                print("imageUrl: ", attachment.url)
                guard let data = try? Data(contentsOf: attachment.url) else { return }
                imageVw?.image = UIImage(data: data) 
            }
        }
    }

}

Have any problem with the implementation, leave a comment below.

Reference: https://medium.com/@mail2ashislaha/rich-push-notification-with-firebase-cloud-messaging-fcm-and-pusher-in-ios-platform-8b4e9922120

Related Posts

0 Comments

12345

    00