58

iOS 10 introduced push notification framework updates,

UserNotificationsUI.framework

As written on apple docs, it lets us customize the appearance of local and remote notifications when they appear on the user’s device.

So if anyone have idea how to display image in push notification when on lock screen. same like andorid push notification are doing.

Thanks,

mfaani
  • 33,269
  • 19
  • 164
  • 293
Parth Pandya
  • 1,460
  • 3
  • 18
  • 34
  • You can watch WWDC developer video. It is explaining at "Rich Notifications" lesson. – Tolgay Toklar Jun 16 '16 at 17:35
  • 2
    If someone needs: - I fond below blogpost and solved the problem: (Load image from url of remote notification) [http://www.avanderlee.com/ios-10/rich-notifications-ios-10/](http://www.avanderlee.com/ios-10/rich-notifications-ios-10/) And don't forget to add a line in your payload : "mutable_content": true, – Touhid Jan 29 '19 at 10:08
  • Documentation: https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/generating_a_remote_notification and https://developer.apple.com/documentation/usernotifications/modifying_content_in_newly_delivered_notifications – Nike Kov Jul 18 '19 at 15:34
  • 3
    The top answer is MISLEADING. Why? Because the OP is asking about **remote** notifications. But the answer is mainly is showing how the image is attached and baked in from when the notification was created — **locally**. The only way to get a remote notification show its image is to have a `NotificationServiceExtension`. A `NotificationContentExtension` won't work because it's just to render existing content passed to it. The attachment has to be passed either locally or downloaded in the `NotificationServiceExtension`. For more on that see https://developer.apple.com/videos/play/wwdc2016/708/ – mfaani Feb 27 '20 at 18:44

5 Answers5

91

If you want to customize the appearance of local and remote notifications, perform the following steps:

  1. Create a UNNotificationCategory and add to the UNUserNotificationCenter category:

    let newCategory = UNNotificationCategory(identifier: "newCategory",
                                             actions: [ action ],
                                             minimalActions: [ action ],
                                             intentIdentifiers: [],
                                             options: [])
    
    let center = UNUserNotificationCenter.current()
    
    center.setNotificationCategories([newCategory])
    
  2. Create a UNNotificationContentExtension:

enter image description here

then use code or storyboard to customize your UIViewController.

  1. Add category to UNNotificationContentExtension's plist:

enter image description here

4.Push Notification

Local Notification

Create a UNMutableNotificationContent and set the categoryIdentifier to "newCategory" which includes UNUserNotificationCenter's categories and UNNotificationContentExtension's plist:

let content = UNMutableNotificationContent()
content.title = ...
content.body = ...
content.categoryIdentifier = "newCategory"

let request = UNNotificationRequest.init(identifier: "newNotificationRequest", content: content, trigger: nil)

let center = UNUserNotificationCenter.current()
center.add(request)

Remote Notification

Set "mutable-content : 1" and "category : newCategory". Note that the category value is set to "newCategory" which matches what you previously added to UNUserNotificationCenter and UNNotificationContentExtensions plist.

Example:

 {
    "aps" : {
        "alert" : {
        "title" : "title",
        "body" : "Your message Here"
        },
        "mutable-content" : "1",
        "category" : "newCategory"
    },
    "otherCustomURL" : "http://www.xxx.jpg"
 }
  1. Note: you need a device or simulator which supports 3DTouch, otherwise you can't show a custom UNNotificationContentExtension viewcontroller.(In iOS10 Beta1, it`s not work. But now this work without 3d touch)

And ... if you just want to show an image on a push notification displayed on the lock screen, you need to add UNNotificationAttachment:

let content = UNMutableNotificationContent()
content.title = ...
content.body = ...
content.categoryIdentifier = "newCategory"

let fileURL: URL = ... //  your disk file url, support image, audio, movie

let attachement = try? UNNotificationAttachment(identifier: "attachment", url: fileURL, options: nil)
content.attachments = [attachement!]

let request = UNNotificationRequest.init(identifier: "newNotificationRequest", content: content, trigger: nil)

let center = UNUserNotificationCenter.current()
center.add(request)

enter image description here

For more detail feature,Demo

maquannene
  • 2,257
  • 1
  • 12
  • 10
  • correct me if I am wrong. in point #5 you are saying none of this can be accomplished in a device that does not have 3d touch ? – Jesus Rodriguez Dec 16 '16 at 15:28
  • 1
    @maquannene I'm pretty sure you have to set `"mutable-content": 1` ; i.e., `1` the integer, not `"1"` the string, or am I incorrect? – BigRon Dec 21 '16 at 17:42
  • @JesusAdolfoRodriguez I write this answer in iOS10 Beta1, and apple change it. This works without 3d touch when system greater than iOS10 Beta1. – maquannene Mar 06 '17 at 02:15
  • 1
    what is the "attachement" in UNNotificationAttachment - identifier...? Im getting error in this line -(unexpectedly found nil while unwrapping an Optional value) – Abirami Bala Jun 03 '17 at 13:35
  • @AbiramiBala: Have you solved that problem i also getting crash there – Abhishek Thapliyal Jun 27 '17 at 11:31
  • 1
    @maquannene : can you add a simple demo project for showing image in Remote Notification? – Abhishek Thapliyal Jun 28 '17 at 07:10
  • @AbhishekThapliyal. yes, Solved, please go through this link, ask me, if you need i can share a sample code. Thanks... – Abirami Bala Jun 30 '17 at 07:04
  • @AbiramiBala : Sure share me the link – Abhishek Thapliyal Jun 30 '17 at 11:25
  • How to add Application extension in XCode-9? – Alok Nov 10 '17 at 07:04
  • @Alok File->New->Target. Then you have to find the Notification Content Extension or Notification Service Extension (depend on your needs). –  Mar 12 '18 at 15:01
  • @maquannene i tried several ways to implement Rich Push notification in Objective C but i cant find it from anywhere.can you please share any solution to implement this code in objective C – Sibin Francis Apr 17 '18 at 12:41
  • have i make certificate which make new notificationExtension and ServiceExtension ? – amisha.beladiya May 24 '18 at 08:43
  • @maquannene Is it possible to send image via Firebase console? – Ashkan Sarlak Aug 26 '18 at 15:14
  • how make certificate for service and content extension?..i implement using thses demo. but app is not running without certificate for service and content extension – kajal Nov 12 '18 at 05:25
  • i have set remote in urlSource in your demo code but app is crash – Ravi Padsala May 01 '19 at 06:09
  • Demo project which you given is full of error,it will be much helpful if you provide error free github projects – Gowtham May 08 '19 at 06:22
  • 3
    This answer is MISLEADING. Why? Because the OP is asking about **remote** notifications. But the answer is mainly is showing how the image is attached and baked in from when the notification was created — **locally**. The only way to get a remote notification show its image is to have a `NotificationServiceExtension`. A `NotificationContentExtension` won't work because it's just to render existing content passed to it. The attachment has to be passed either locally or downloaded in the `NotificationServiceExtension`. For more on that see https://developer.apple.com/videos/play/wwdc2016/708/ – mfaani Feb 27 '20 at 18:46
12

Actually if you are setting up a local notification and you're just interested in having an image show up in the notification itself, you don't have to bother with NotificationsUI.framework or UNNotificationContentExtensions at all. That is only useful if you want a custom UI when the user 3D touches or expands the notification.

To add an image that is already on the device (either shipped with the app, or generated/stored by the app at some point before the notification is created), then you only need to add a UNNotificationAttachment with a file URL where the path ends in .png (or .jpg will likely work too?). Something like this:

UNMutableNotificationContent *content = [UNMutableNotificationContent new];
content.title = @"Title";
content.body = @"Body";
content.sound = [UNNotificationSound defaultSound];
NSURL *imageURL = [NSURL URLWithString:@"file:/some/path/in/app/image.png"];
NSError *error;
UNNotificationAttachment *icon = [UNNotificationAttachment attachmentWithIdentifier:@"image" URL:imageURL options:nil error:&error];
if (error)
{
    NSLog(@"error while storing image attachment in notification: %@", error);
}
if (icon)
{
    content.attachments = @[icon];
}

Then when the notification appears, the image will show up on the right-hand side of the notification banner like it does for Messages notifications. And you don't have to jump through all of the hoops of setting up a content extension with a categoryIdentifier, etc.

EDIT: Updated to add that this is only a valid solution for local notifications.

Greg G
  • 461
  • 4
  • 14
5

You have to do some work on creating push notification and also when you are handling.

  1. When you creating payload you need to add extra attribute attachment, something like below:

    {        
        aps : {
            alert: { },
            mutable-content:1
        }
        my-attachment = "url to resource"
    }
    
  2. When you receive notification system will call didReceive method of service extension, override notification extension didReceive method like this

    public func didReceive(_ request:UNNotificationRequest, withContentHandler contentHandler:(UNNotificatinContent) -> Void) {
        let fileUrl = //
        let attachment = UNNotificationAttachment(identifier : "image", url: fileUrl, options: nil)
        let content = request.content.mutableCopy as! UNMutableNotificationContent
        content.attachment = [attachment]
        contentHandler(content)
    }
    

Here is WWDC video talk on this topic.

Luke
  • 3,375
  • 2
  • 22
  • 22
Adnan Aftab
  • 14,377
  • 4
  • 45
  • 54
1

With the version of Netmera SDK 3.14.4, you don't need to add a bridging header file to use iOS 10 media push. You should only implement the following methods in your Notification Service Extension to receive rich media push. You can reach for both Swift and Objective-C.

Step 1

Remove the Objective-C Bridging Header file from the project and add: import NetmeraNotificationServiceExtension in the NotificationService.swift file.

target 'your_service_extension_target_name' do

 pod "Netmera/NotificationServiceExtension"

end

After adding the previous line to your Podfile, pod update is used.

Step 2

Make sure you have Xcode 8 or a higher version installed. If not, upgrade your Xcode installation to use iOS10 media push on your application. First you should create a new Notification Service Extension to your application. In order to do that, you should follow those steps:

  • open Xcode and navigate to "File" -> "New" -> "Target"

enter image description here

  • choose Notification Service Extension from the available options.

enter image description here

Step 3

A new class named "NotificationService" will be created, which should be extended from the "NetmeraNotificationServiceExtension" class. Your NotificationService class should look like the following,

class NotificationService : NetmeraNotificationServiceExtension {

    override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (_ contentToDeliver: UNNotificationContent) -> Void) {
        super.didReceive(request, withContentHandler: contentHandler)
    }

    override func serviceExtensionTimeWillExpire() {
        super.serviceExtensionTimeWillExpire()
    }

}

Link the "Netmera.framework" to the Notification Service Extension. To do this, add your Notification Service Extension as a target to your Podfile by including the following line:

pod "Netmera/NotificationServiceExtension"

Update your Podfile to install the necessary dependencies and perform the linking process.

And for more to send carousel, slider notification you can review here.

Phil Dukhov
  • 67,741
  • 15
  • 184
  • 220
ecem
  • 11
  • 3
-2

Implement your notification's custom view using a UIViewController that conforms to UNNotificationContentExtension.

See https://developer.apple.com/reference/usernotificationsui/unnotificationcontentextension

Peter Cetinski
  • 2,328
  • 14
  • 8