How to get image in iOS push notification

How to get image in iOS push notification
January 10, 2020 7 Comments Development,iOS Development Pushpendra Kumar

Hello Developers, Here I am giving you quick review regarding how to get image in iOS push notification. This procedure called rich notification in iOS. So let’s come the point directly without waisting time.

At the very first you have to create all the certificate on the apple developer account. In Addition, You have to create one certificate for iOS Push notification. And After that you have to create keys. Once you completed with this process then follow the below steps.

How to get image in iOS push notification with procedure

  • Click on the Project Folder 
  • Click on Signing & Capability
  • Add New Capability from + Capability button
  • Now Type Push Notification
  • Add Background Modes in same way and Check Remote Notification
how to enable push notification in Xcode
how to enable push notification in Xcode

After that, Doing all this work move to next task.

Create new target in Xcode for notification

  • Add new Target in your project, Notification Content Extension
  • Add one more new target in your project Notification Service Extension
  • Change all the target to version 10.0
  • Also Change the Architecture with arm64 in both target. In addition Click on Main Project Target and select Build Setting Tab and Go to the Architectures. Here you need to write arm64 for every target.
Create new target in iOS
Create new target in iOS
Create notification service in ios
Create notification service in ios

After that, Add UNNotificationExtensionCategory  in Notification Content Extension Info.plist, As mentioned into the below image.

Add UNNotificationExtensionCategory  in Notification Content Extension

add notification category in info.plist
Add notification category in info.plist

After that, Now let’s move to the coding part. Go to NotificationService Swift file and update following code.

import UserNotifications
class NotificationService: UNNotificationServiceExtension {

  private var contentHandler: ((UNNotificationContent) -> Void)?
    private var bestAttemptContent: UNMutableNotificationContent?

    override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
        print("Notification Recived")
        self.contentHandler = contentHandler
        bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)

        defer {
            contentHandler(bestAttemptContent ?? request.content)
        /// Add the category so the "Open Board" action button is added.
        bestAttemptContent?.categoryIdentifier = "content_added_notification"

        guard let attachment = request.attachment else { return }

        bestAttemptContent?.attachments = [attachment]
    override func serviceExtensionTimeWillExpire() {
        print("TIME OUT")
        // 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 {
extension UNNotificationRequest {
    var attachment: UNNotificationAttachment? {
        print("Notification Recived")
        guard let attachmentURL = content.userInfo["image_url"] as? String, let imageData = try? Data(contentsOf: URL(string: attachmentURL)!) else {
            return nil
        print("IMAGE DATA - ", imageData)
        return try? UNNotificationAttachment(data: imageData, options: nil)

extension UNNotificationAttachment {
    convenience init(data: Data, options: [NSObject: AnyObject]?) throws {
        let fileManager = FileManager.default
        let temporaryFolderName = ProcessInfo.processInfo.globallyUniqueString
        let temporaryFolderURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(temporaryFolderName, isDirectory: true)

        try fileManager.createDirectory(at: temporaryFolderURL, withIntermediateDirectories: true, attributes: nil)
        let imageFileIdentifier = UUID().uuidString + ".jpg"
        let fileURL = temporaryFolderURL.appendingPathComponent(imageFileIdentifier)
        try data.write(to: fileURL)
        try self.init(identifier: imageFileIdentifier, url: fileURL, options: options)

Great, Finally Change your NotificationViewController Which is inside Your Content Extension

import UIKit
import UserNotifications
import UserNotificationsUI

class NotificationViewController: UIViewController, UNNotificationContentExtension {

    @IBOutlet weak var img_notification: UIImageView!
    @IBOutlet var label: UILabel?
    override func viewDidLoad() {
        // Do any required interface initialization here.
    func didReceive(_ notification: UNNotification) {
        self.label?.text = notification.request.content.body
        let attachmentURL = notification.request.content.userInfo["image_url"] as? String
        if attachmentURL != nil {
            let data = try? Data(contentsOf: URL(string: attachmentURL ?? "https://example.default.image/image.png")!)
            if data != nil {
                self.img_notification.image = UIImage(data: data!)

Wonderful, You almost completed the coding part. For your kind information I want to tell you that in above code NotificationViewController.swift, I have use custom image_view. I Have given the reference to this from my MainInterface.storyboard

Please look into the below image.

How to get image in iOS push notification
How to get image in iOS push notification

In Addition, I want to tell you that. I have set this image 0 from to, 0,0 From let and right. And here I have give constant heigh 200. For your kind information I did not set any anchor from the bottom.

FCM generates an Instance ID, which is used as a registration token within FCM. When an Instance ID is generated the library will upload the identifier and configuration data to Firebase.If you want to get an explicit opt-in before using Instance ID, you can prevent generation at configure time by disabling FCM (and on Android, Analytics). To do this, add a metadata value to your Info.plist (not your GoogleService-Info.plist)

FirebaseMessagingAutoInitEnabled = NO

Now Finally, Have look on your payload. I have send this notification from Post Man. If you want to do the same then follow the given procedure on this link – LINK.

	 "to" : "f2dejETPd9Q:APA91bGYFEl4............cZX-QO_",
	 "content_available": true,
	 "mutable_content": true,
	 "category": "content_added_notification",
		"notification" : {
			 "title" : "My Notification title",
			 "body" : "You have grand welcome bonus!",
			 "sound" : "notification_sound"
		"data": {
			"title" : "My Notification title",
			"message" : "You have grand welcome bonus!",

Great, In Conclusion I hope you are very clear about the push notification. If you have any question please comment below any time. Thanks for being here. Have a great time to you 😎😎😎

In Addition, If you are looking something interesting. Please follow the below links.

About The Author
Pushpendra Kumar I am passionate about mobile application development and professional developer at Colour Moon Technologies Pvt Ltd ( This website I have made so that I can meet with new challenges and can share here.
Leave Comment
  1. 1

    White Label SEO

    Awesome post! Keep up the great work! 🙂

  2. 1


    Great content! Super high-quality! Keep it up! 🙂

  3. 1

    Clear Phone Cases

    Wonderful article and I really appreciate your hard work.

    King regards,
    Demir Griffin

  4. 1


    Great tutorial, I have one doubt, actually i used default push notification in my project, it’s working properly, then how to override that code instead of this new code? i mean is default code is necessary ?

    1. 1

      Pushpendra Kumar

      No, If you are going to use this trick then default code is not required, You can completely remove default code as you are saying and you can use on this code. This is also native code, But with some advanced version..!! 😊😊

  5. 1


    Thank you so much, followed exactly the tutorial said and worked perfectly. And this being according to the latest code makes it more reliable solution. Thanks again.

  6. 1


    Like!! Really appreciate you sharing this blog post.Really thank you! Keep writing.


Leave a reply

Your email address will not be published. Required fields are marked *