Chat APIs and In-app Messaging SDKs for Developers, by Developers

Applozic powers multi-platform Chat APIs and in-app Messaging SDKs for Android, iOS and the Web that will enable you to build advanced in-app chat solutions your users will love.

Integrate chat in your application with completely customizable UI kits, powerful messaging APIs and SDKs, developed with exceptional security measures in mind.

Documentation    API Explorer

Notifications (CoreSDK)

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 an APNs certificate in your Apple developer account.
Visit

  1. Visit this link, select Apple Push Notification service SSL (Sandbox & Production), and create.

A sample is shown below shows what your certificate should look like once you create it

The above created Apple Push Notification service will work for both Production and Development

📘

Note: Supported format for the APNS certificate is .p12

Export a .p12 file from keychains and upload it to Applozic Console

The p12 files are required for authenticating Apple servers for sending APNs push notifications to devices will guide how to export p12 file from Keychains for uploading to the Applozic console.

Follow these steps for export Apple push service certificate p12 file:

A. Open Keychain Access on your Mac and go to login > Select My Certificates.

B. Find the Apple push services certificate and which you added, right-click on the certificate, and then select the Export **** option from the menu to get a .p12 file and type a name for the file and save it with the password.

Upload APNs Certificates

Upload your push notification certificate (mentioned above-exported p12 file) to Applozic console by referring to the below-given image, in order to enable real-time notification.

Go to Applozic Console ->Click on Settings -> Chat--> Notifications -> Click Add Certificate
Upload APNS .p12 Certificate of Apple push services (Sandbox & Production) in Production and Development same p12 file in both.

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

  1. Push Notifications
  2. 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];
      
  // Added ALPushNotificationHandler in version 8.0.0+
   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();
  
    // Added ALPushNotificationHandler in version 8.0.0+
    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.

❗️

Upload APNs certificates before going to next steps

Check out this below link for uploading.
https://docs.applozic.com/docs/notifications-1#setting-up-apns-certificates

❗️

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 {
        
        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 *)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];

    NSDictionary * userInfo = response.notification.request.content.userInfo;

    if ([service isApplozicNotification: userInfo]) {
        [self.applozicClient notificationArrivedToApplication:[UIApplication sharedApplication] withDictionary:response.notification.request.content.userInfo];
        completionHandler();
    } else {
        //Handle your noticiation

        completionHandler();
    }

}
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 6 days ago



Notifications (CoreSDK)


Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.