Add Notification Service Extension

When push notification arrives in an iOS app, you may want to be able to download content in response to it or edit the content before it’s shown to the user. In iOS 10 and later, Apple allows apps to do that using new Notification Service Extension.

The Following guide will help you to set up a project to display image in notification banner. The following steps describe how to enable group extension and notification service in the iOS application.

Setting up Xcode project

Step 1. Add new target

Step 2. Select Notification Service Extension

Step 3. Enter a name for your target (E.x. DemoNotificationServiceExtension)

Step 4. Select Cancel(By this work you do not change the project target)

Step 5. Select your project file, after that, select target which dependent by Notification Service Extension and change its setting as follows.

You can see a new directory on your project with Notification Service Extension name.

Step 6. Change NotificationService.m as follow.

#import "NotificationService.h"
@import Hengam;
@interface NotificationService ()
@property (nonatomic, strong) void (^contentHandler)(UNNotificationContent *contentToDeliver);
@property (nonatomic, strong) UNMutableNotificationContent *bestAttemptContent;
@end
@implementation NotificationService
- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
    self.contentHandler = contentHandler;
    self.bestAttemptContent = [request.content mutableCopy];
    [HengamClient.shared didReceiveNotificationExtensionRequest:self.bestAttemptContent :self.contentHandler];
}
- (void)serviceExtensionTimeWillExpire {
    self.contentHandler(self.bestAttemptContent);
}
@end
import UserNotifications
import Hengam
class NotificationService: UNNotificationServiceExtension {
    var contentHandler: ((UNNotificationContent) -> Void)?
    var bestAttemptContent: UNMutableNotificationContent?
    override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
        self.contentHandler = contentHandler
        self.bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)

        if let bestAttemptContent = self.bestAttemptContent {
            HengamClient.shared.didReceiveNotificationExtensionRequest(mutableContent: bestAttemptContent, contentHandler: contentHandler)
        }
    }
    override func serviceExtensionTimeWillExpire() {
        if let contentHandler = self.contentHandler, let bestAttemptContent =  self.bestAttemptContent {
            contentHandler(bestAttemptContent)
        }
    }
}