iOS
APNS Push Notification in iOS
This section describes the process that needs to be followed to receive push notifications for your chat within your app.
Setting up APNs Certificates
Applozic sends the payload to Apple servers which then sends the push notification to your user's device.
Creating APNs certificates
For Apple to send these notifications, you would have to create APNs certificate in your Apple developer account.
Visit
- https://developer.apple.com/account/ios/certificate/development, to create development APNs certificate
A sample is shown below shows what your certificate should look like once you create it


- https://developer.apple.com/account/ios/certificate/distribution, to create distribution certificate
a sample is shown below


Note: Supported format for APNS certificate is .p12.
Upload APNs Certificates
Upload your push notification certificates (mentioned above) to Applozic Dashboard by referring to below-given image, in order to enable real-time notification.
Go to [Applozic Dashboard](https://console.applozic.com/login) ->Click on Settings -> Push Notification ->
Upload APNS Certificate for Development and Distribution environment.


Updating Capabilities
Post setting up APNs, the next step is to enable push notifications within your project. To do that
Click on your project ----> Click on Capabilities and enable
- Push Notifications
- Background Modes - Fetch and Remote notification
Following screenshots would be of help.




Have Question Or Suggestion?
You can drop us your query at [email protected]
Pre-built customizable chat UI - Message Notification
Push Notifications
Push notification setup is rather straightforward, all you need to do is to find "AppDelegate" file in your project and follow all the instructions below.
Add the following import lines at the top of your AppDelegate.m file.
#import <Applozic/Applozic.h>
#import <UserNotifications/UserNotifications.h>
import Applozic
a) Send device token to Applozic server:
In your AppDelegate’s didRegisterForRemoteNotificationsWithDeviceToken method send device registration to Applozic server after you get deviceToken from APNS.
In case you don't find didRegisterForRemoteNotificationsWithDeviceToken method then create the method and copy the below code within the same
Sample code is as below:
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)
deviceToken {
const unsigned *tokenBytes = [deviceToken bytes];
NSString *hexToken = [NSString stringWithFormat:@"%08x%08x%08x%08x%08x%08x%08x%08x",
ntohl(tokenBytes[0]), ntohl(tokenBytes[1]), ntohl(tokenBytes[2]),
ntohl(tokenBytes[3]), ntohl(tokenBytes[4]), ntohl(tokenBytes[5]),
ntohl(tokenBytes[6]), ntohl(tokenBytes[7])];
NSString *apnDeviceToken = hexToken;
NSLog(@"apnDeviceToken: %@", hexToken);
if (![[ALUserDefaultsHandler getApnDeviceToken] isEqualToString:apnDeviceToken]) {
ALRegisterUserClientService *registerUserClientService = [[ALRegisterUserClientService alloc] init];
[registerUserClientService updateApnDeviceTokenWithCompletion
:apnDeviceToken withCompletion:^(ALRegistrationResponse
*rResponse, NSError *error) {
if (error) {
NSLog(@"%@",error);
return;
}
NSLog(@"Registration response%@", rResponse);
}];
}
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
{
NSLog("Device token data :: \(deviceToken.description)")
var deviceTokenString: String = ""
for i in 0..<deviceToken.count
{
deviceTokenString += String(format: "%02.2hhx", deviceToken[i] as CVarArg)
}
NSLog("Device token :: \(deviceTokenString)")
if (ALUserDefaultsHandler.getApnDeviceToken() != deviceTokenString)
{
let alRegisterUserClientService: ALRegisterUserClientService = ALRegisterUserClientService()
alRegisterUserClientService.updateApnDeviceToken(withCompletion: deviceTokenString, withCompletion: { (response, error) in
if error != nil {
NSLog("Error in Registration: %@", error)
}
NSLog("Registration Response :: \(response)")
})
}
}
b) Receiving push notification:
Once your app receives notification, pass it to Applozic handler for chat notification processing.
- (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary*)dictionary {
NSLog(@"Received notification WithoutCompletion: %@", dictionary);
ALPushNotificationService *pushNotificationService = [[ALPushNotificationService alloc] init];
[pushNotificationService notificationArrivedToApplication:application withDictionary:dictionary];
}
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler {
NSLog(@"Received notification Completion: %@", userInfo);
ALPushNotificationService *pushNotificationService = [[ALPushNotificationService alloc] init];
[pushNotificationService notificationArrivedToApplication:application withDictionary:userInfo];
completionHandler(UIBackgroundFetchResultNewData);
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification*)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {
ALPushNotificationService *pushNotificationService = [[ALPushNotificationService
alloc] init];
NSDictionary *userInfo = notification.request.content.userInfo;
if ([pushNotificationService isApplozicNotification:userInfo]) {
[pushNotificationService notificationArrivedToApplication:[UIApplication sharedApplication] withDictionary:userInfo];
completionHandler(UNNotificationPresentationOptionNone);
return;
}
completionHandler(UNNotificationPresentationOptionAlert|UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound);
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(nonnull UNNotificationResponse* )response withCompletionHandler:(nonnull void (^)(void))completionHandler {
ALPushNotificationService *pushNotificationService = [[ALPushNotificationService
alloc] init];
NSDictionary *userInfo = response.notification.request.content.userInfo;
if ([pushNotificationService isApplozicNotification:userInfo]) {
[pushNotificationService notificationArrivedToApplication:[UIApplication sharedApplication] withDictionary:userInfo];
completionHandler();
return;
}
completionHandler();
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
print("Received notification :: \(userInfo.description)")
let alPushNotificationService: ALPushNotificationService = ALPushNotificationService()
alPushNotificationService.notificationArrived(to: application, with: userInfo)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
print("Received notification With Completion :: \(userInfo.description)")
let alPushNotificationService: ALPushNotificationService = ALPushNotificationService()
alPushNotificationService.notificationArrived(to: application, with: userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let pushNotificationService = ALPushNotificationService()
let userInfo = notification.request.content.userInfo
if pushNotificationService.isApplozicNotification(userInfo) {
pushNotificationService.notificationArrived(to: UIApplication.shared, with: userInfo)
completionHandler([])
return
}
completionHandler([.alert, .badge, .sound])
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let pushNotificationService = ALPushNotificationService()
let userInfo = response.notification.request.content.userInfo
if pushNotificationService.isApplozicNotification(userInfo) {
pushNotificationService.notificationArrived(to: UIApplication.shared, with: userInfo)
completionHandler()
return
}
completionHandler()
}
c) Handling app launch on notification click and register remote notification :
#import <UserNotifications/UserNotifications.h>
@interface AppDelegate () <UNUserNotificationCenterDelegate>
// Appdelegate add UNUserNotificationCenterDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
// checks wheather app version is updated/changed then makes server call setting VERSION_CODE
[ALRegisterUserClientService isAppUpdated];
[self registerForNotification];
// Register for Applozic notification tap actions and network change notifications
ALAppLocalNotifications *localNotification = [ALAppLocalNotifications appLocalNotificationHandler];
[localNotification dataConnectionNotificationHandler];
ALPushNotificationHandler *pushNotificationHandler = [ALPushNotificationHandler shared];
[pushNotificationHandler dataConnectionNotificationHandler];
// Override point for customization after application launch.
NSLog(@"launchOptions: %@", launchOptions);
if (launchOptions != nil) {
NSDictionary *dictionary = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (dictionary != nil) {
NSLog(@"Launched from push notification: %@", dictionary);
ALPushNotificationService *pushNotificationService = [[ALPushNotificationService alloc] init];
BOOL applozicProcessed = [pushNotificationService processPushNotification:dictionary updateUI:[NSNumber numberWithInt:APP_STATE_INACTIVE]];
//IF not a appplozic notification, process it
if (!applozicProcessed) {
//Note: notification for app
}
}
}
return YES;
}
-(void)registerForNotification
{
if(@available(iOS 10.0, *))
{
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
[center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error)
{
if(!error)
{
dispatch_async(dispatch_get_main_queue(), ^ {
[[UIApplication sharedApplication] registerForRemoteNotifications]; // required to get the app to do anything at all about push notifications
NSLog(@"Push registration success." );
});
}
else
{
NSLog(@"Push registration FAILED" );
NSLog(@"ERROR: %@ - %@", error.localizedFailureReason, error.localizedDescription );
NSLog(@"SUGGESTIONS: %@ - %@", error.localizedRecoveryOptions, error.localizedRecoverySuggestion );
}
}];
}
else
{
[[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
}
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,UNUserNotificationCenterDelegate
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
//Register for notification
registerForNotification()
// Override point for customization after application launch.
let alApplocalNotificationHnadler : ALAppLocalNotifications = ALAppLocalNotifications.appLocalNotificationHandler();
alApplocalNotificationHnadler.dataConnectionNotificationHandler();
let pushNotificationHandler = ALPushNotificationHandler.shared()
pushNotificationHandler.dataConnectionNotificationHandler()
if (launchOptions != nil)
{
let dictionary = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? NSDictionary
if (dictionary != nil)
{
print("launched from push notification")
let alPushNotificationService: ALPushNotificationService = ALPushNotificationService()
let appState: NSNumber = NSNumber(value: 0 as Int32)
let applozicProcessed = alPushNotificationService.processPushNotification(launchOptions,updateUI:appState)
if (!applozicProcessed)
{
//Note: notification for app
}
}
}
return true
}
func registerForNotification() {
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
if granted {
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
} else {
// Fallback on earlier versions
let settings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
UIApplication.shared.registerUserNotificationSettings(settings)
UIApplication.shared.registerForRemoteNotifications()
}
}
Note: Above didFinishLaunchingWithOptions apploizc method code is required in all the cases if your using any other push notification setup like firebase or one signal or any other it needs to be added in your Appdelegate file
d) AppDelegate changes to observe background/foreground notification:
Background Notification
- (void)applicationDidEnterBackground:(UIApplication *)application {
ALRegisterUserClientService *registerUserClientService = [[ALRegisterUserClientService alloc] init];
[registerUserClientService disconnect];
[[NSNotificationCenter defaultCenter] postNotificationName:@"APP_ENTER_IN_BACKGROUND" object:nil];
}
func applicationDidEnterBackground(_ application: UIApplication) {
print("APP_ENTER_IN_BACKGROUND")
NotificationCenter.default.post(name: Notification.Name(rawValue: "APP_ENTER_IN_BACKGROUND"), object: nil)
}
Foreground Notification
- (void)applicationWillEnterForeground:(UIApplication *)application {
ALRegisterUserClientService *registerUserClientService = [[ALRegisterUserClientService alloc] init];
[registerUserClientService connect];
[ALPushNotificationService applicationEntersForeground];
[[NSNotificationCenter defaultCenter] postNotificationName:@"APP_ENTER_IN_FOREGROUND" object:nil];
[application setApplicationIconBadgeNumber:0];
}
func applicationWillEnterForeground(_ application: UIApplication) {
ALPushNotificationService.applicationEntersForeground()
print("APP_ENTER_IN_FOREGROUND")
NotificationCenter.default.post(name: Notification.Name(rawValue: "APP_ENTER_IN_FOREGROUND"), object: nil)
UIApplication.shared.applicationIconBadgeNumber = 0
}
e) Save Context when app terminates
- (void)applicationWillTerminate:(UIApplication *)application {
[[ALDBHandler sharedInstance] saveContext];
}
func applicationWillTerminate(application: UIApplication) {
ALDBHandler.sharedInstance().saveContext()
}
Disable Notification
In order to disable the incoming push notification alert or only notification sound, you need to update notification mode. Below are the possible values of notification mode.
Notification Mode | Explanation |
---|---|
0 | Enable notification with sound (Default) |
1 | Enable notification without sound |
2 | Disable notification (No Alert) |
[ALRegisterUserClientService updateNotificationMode:modeValue withCompletion:^(ALRegistrationResponse *response, NSError *error) {
NSLog(@"RESPONSE :: %@",response.message);
NSLog(@"RESPONSE_ERROR :: %@",error.description);
if(!error)
{
[ALUserDefaultsHandler setNotificationMode:modeValue];
}
else
{
//Error updating notification mode...
}
}];
ALRegisterUserClientService.updateNotificationMode(modeValue, withCompletion: {
response, error in
if(error != nil) {
ALUserDefaultsHandler.setNotificationMode(modeValue)
} else {
}
})
Have Question Or Suggestion?
You can drop us your query at [email protected]
Build your UI from scratch - Message Notification
Push Notifications
To set up push notification all you need to do is to find "AppDelegate" file in your project and follow the instructions below.
Setup ApplozicClient
Note: You need to setup ApplozicClient before using the methods refer to this link
a) Send device token to Applozic server:
In your AppDelegate’s didRegisterForRemoteNotificationsWithDeviceToken method, send device registration to Applozic server after you get deviceToken from APNS.
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)
deviceToken {
const unsigned *tokenBytes = [deviceToken bytes];
NSString *hexToken = [NSString stringWithFormat:@"%08x%08x%08x%08x%08x%08x%08x%08x",
ntohl(tokenBytes[0]), ntohl(tokenBytes[1]), ntohl(tokenBytes[2]),
ntohl(tokenBytes[3]), ntohl(tokenBytes[4]), ntohl(tokenBytes[5]),
ntohl(tokenBytes[6]), ntohl(tokenBytes[7])];
NSString *apnDeviceToken = hexToken;
NSLog(@"apnDeviceToken: %@", hexToken);
if (![[ALUserDefaultsHandler getApnDeviceToken] isEqualToString:apnDeviceToken]) {
ALRegisterUserClientService *registerUserClientService = [[ALRegisterUserClientService alloc] init];
[registerUserClientService updateApnDeviceTokenWithCompletion
:apnDeviceToken withCompletion:^(ALRegistrationResponse
*rResponse, NSError *error) {
if (error) {
NSLog(@"%@",error);
return;
}
NSLog(@"Registration response%@", rResponse);
}];
}
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
{
NSLog("Device token data :: \(deviceToken.description)")
var deviceTokenString: String = ""
for i in 0..<deviceToken.count
{
deviceTokenString += String(format: "%02.2hhx", deviceToken[i] as CVarArg)
}
NSLog("Device token :: \(deviceTokenString)")
if (ALUserDefaultsHandler.getApnDeviceToken() != deviceTokenString)
{
let alRegisterUserClientService: ALRegisterUserClientService = ALRegisterUserClientService()
alRegisterUserClientService.updateApnDeviceToken(withCompletion: deviceTokenString, withCompletion: { (response, error) in
if error != nil {
NSLog("Error in Registration: %@", error)
}
NSLog("Registration Response :: \(response)")
})
}
}
b) Handling app launch on notification :
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
if (launchOptions != nil)
{
NSDictionary *dictionary = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (dictionary != nil)
{
NSLog(@"Launched from push notification: %@", dictionary);
[self.applozicClient notificationArrivedToApplication:application withDictionary:dictionary];
}
}
return YES;
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
ALMessageService.getLatestMessage(forUser: ALUserDefaultsHandler.getDeviceKeyString()) { (messages, error) in
if(error == nil){
// Add messages array in your view controller once messges are synced
}
}
if (launchOptions != nil)
{
let dictionary = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? NSDictionary
if (dictionary != nil)
{
applozicClient.notificationArrived(to: application, with: launchOptions)
}
}
return true
}
c) AppDelegate changes to observe background/foreground notification:
Background Notification
- (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary*)dictionary {
[self.applozicClient notificationArrivedToApplication:application withDictionary:dictionary];
}
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler{
[self.applozicClient notificationArrivedToApplication:application withDictionary:userInfo];
completionHandler(UIBackgroundFetchResultNewData);
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler{
ALPushNotificationService * service = [[ALPushNotificationService alloc]init];
ApplozicClient * applozicClient = [[ApplozicClient alloc]init];
NSDictionary * userInfo = response.notification.request.content.userInfo;
if([service isApplozicNotification: userInfo]){
[applozicClient notificationArrivedToApplication:[UIApplication sharedApplication] withDictionary:response.notification.request.content.userInfo];
completionHandler();
}else{
//Handle your noticiation
completionHandler();
}
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any])
{
print("Received notification :: \(userInfo.description)")
applozicClient.notificationArrived(to: application, with: userInfo)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler
completionHandler: @escaping (UIBackgroundFetchResult) -> Void)
{
print("Received notification With Completion :: \(userInfo.description)")
applozicClient.notificationArrived(to: application, with: userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
let service = ALPushNotificationService()
if service.isApplozicNotification(userInfo) {
applozicClient.notificationArrived(to: UIApplication.shared, with: userInfo)
completionHandler()
return
}
completionHandler()
}
d) Add the below code in applicationWillEnterForeground of appDelegate to sync messages
- (void)applicationDidBecomeActive:(UIApplication *)application {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
[ALMessageService getLatestMessageForUser:[ALUserDefaultsHandler getDeviceKeyString] withDelegate:self withCompletion:^(NSMutableArray *messages, NSError *error) {
}];
}
func applicationDidBecomeActive(_ application: UIApplication) {
ALMessageService.getLatestMessage(forUser: ALUserDefaultsHandler.getDeviceKeyString(), with: self) { (array, error) in
}
}
if messages
are there then you can add messages in your view controller once messages are synced.
e) Save Context when app terminates
- (void)applicationWillTerminate:(UIApplication *)application {
[[ALDBHandler sharedInstance] saveContext];
}
func applicationWillTerminate(application: UIApplication) {
ALDBHandler.sharedInstance().saveContext()
}
Updated about 1 year ago