Skip to content

Latest commit

 

History

History
576 lines (391 loc) · 20.1 KB

INTEGRATION-DOC.md

File metadata and controls

576 lines (391 loc) · 20.1 KB

Prerequisites

  • Apps using Applozic can target iOS 8 or later.
  • Xcode 8.0 or later required.

Integrate using:

  1. Objective-C
  2. Swift

Objective-C

Step 1: Chat SDK Installation

Automatic Installation via CocoaPods

i) Open terminal and navigate to your project root directory and run command pod init in terminal

ii) Go to project directory open pod file and add code in that

 pod 'Applozic', '~>4.0.1'
 

iii) Run pod install or pod update to refresh your cocoapods dependencies.

For reference download our sample project here ApplozicCocoaPodDemo

Add Framework Manually

NOTE: This step is needed only when not using cocoapods.

Download Applozic Chat latest framework here and add it to your project.

Note : Framework folder has two frameworks.

  1. Universal framework: Complied for both simultor and real devices.
  2. Archive framework: Complied for real device only. When archiving your app, please use archive framework.

Add framework to your project:

i) Paste Applozic framework to root folder of your project.

ii) Go to Build Phase.

Expand Embedded frameworks and add applozic framework.

dashboard-blank-content

Step 2: Login/Register User

Applozic will create a new user if the user doesn't exists. userId is the unique identifier for any user, it can be anything like email, phone number or uuid from your database.

i) Add Helper Classes:

Download ALChatManager.h and ALChatManager.m file and add to your project.

ALChatManager.h

ALChatManager.m

Change value of applicationID in ALChatManager.h with the Applozic Application Key.

At the top of your Objective‑C source files, use #import "ALChatManager.h"

ii) Login/Register User:

Create applozic user and add details to applozic user object.

  ALUser *alUser = [[ALUser alloc] init];
  [alUser setUserId:@"testUser"]; //NOTE : +,*,? are not allowed chars in userId.
  [alUser setDisplayName:@"Applozic Test"]; // Display name of user 
  [alUser setContactNumber:@""];// formatted contact no
  [alUser setImageLink:@"user_profile_image_link"];// User's profile image link.

Convenient methods are present in ALChatManager.m to register user with applozic. You can Register user to applozic server by using below method from AlChatManager.h.

   NOTE: Replace "applozic-sample-app" by your application key 
ALChatManager * chatManager = [[ALChatManager alloc] initWithApplicationKey:@"applozic-sample-app"];
[chatManager registerUserWithCompletion:user withHandler:^(ALRegistrationResponse *rResponse, NSError *error) {
        
        if (!error)
        {
	   //Applozic registration successful
	   
        }
	else
	{
            NSLog(@"Error in Applozic registration : %@",error.description);
	}
    }];

NOTE: if access token validation is configured from your server then set your server generated token as password at the time of user registration.

i) Set Authentication type to CLIENT in ALChatManager.m

  [ALUserDefaultsHandler setUserAuthenticationTypeId:(short)CLIENT];

ii) Set access token generated as password.

  [user setPassword:<YOUR ACCESS TOKEN>];
  
  [ALUserDefaultsHandler setPassword:<YOUR ACCESS TOKEN>];

Step 3: Initiate Chat

  1. Launch chat list screen:
    [chatManager launchChat:<Your Controller>];
  1. Launch chat with specific user/group:
  NSString * userIdOfReceiver =  @"receiverUserId";
  [chatManager launchChatForUserWithDisplayName:userIdOfReceiver 
  withGroupId:nil  //If launched for group, pass groupId(pass userId as nil)
  andwithDisplayName:nil //Not mandatory, if receiver is not already registered you should pass Displayname.
  andFromViewController:<YOUR CONTROLLER> ];
  

Step 4: Push Notification Setup

Upload your push notification certificate to Applozic Dashboard page under 'Edit Application' section in order to enable real time notification.

	Go to Applozic Dashboard -> Edit Application -> Push Notification -> 
	Upload APNS Certificate for Development and Distribution environments
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. 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);                  
 
   //TO AVOID Multiple call to server check if previous apns token is same as recent one, 
   If its different then call Applozic server.          

    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 from server:%@", rResponse);                         
    }]; 
  } 
}                                 

b) Receiving push notification :

Once your app receive 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);
    
}

c) Handling app launch on notification click :

- (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];
    
    // Register for Applozic notification tap actions and network change notifications
    ALAppLocalNotifications *localNotification = [ALAppLocalNotifications appLocalNotificationHandler];
    [localNotification 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;
}

d) AppDelegate changes to observe background/foreground notification.

- (void)applicationDidEnterBackground:(UIApplication *)application {
    
    ALRegisterUserClientService *registerUserClientService = [[ALRegisterUserClientService alloc] init];
    [registerUserClientService disconnect];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"APP_ENTER_IN_BACKGROUND" object:nil];
}
- (void)applicationWillEnterForeground:(UIApplication *)application {

    ALRegisterUserClientService *registerUserClientService = [[ALRegisterUserClientService alloc] init];
    [registerUserClientService connect];
    [ALPushNotificationService applicationEntersForeground];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"APP_ENTER_IN_FOREGROUND" object:nil];
}

e) Save Context when app terminates

- (void)applicationWillTerminate:(UIApplication *)application {

    [[ALDBHandler sharedInstance] saveContext];
}
f) APNs Certification Type Setup :

In ALChatManager change setting according to your certificate and profile used:

Method Name:

-(void)ALDefaultChatViewSettings

Code to set mode depending on your code signing and profile used:

For Development:
    [ALUserDefaultsHandler setDeviceApnsType:(short)DEVELOPMENT];

For Distribution:
    [ALUserDefaultsHandler setDeviceApnsType:(short)DISTRIBUTION];

Step 5: Add permission for camera,photo library ,Micro phone, contacts and location.

In your info.plist add these permission for diffrent type of attachments.

<key>NSCameraUsageDescription</key>
	<string>Allow Camera</string>
	<key>NSContactsUsageDescription</key>
	<string>Allow Contacts</string>
	<key>NSLocationWhenInUseUsageDescription</key>
	<string>Allow location sharing!!</string>
	<key>NSMicrophoneUsageDescription</key>
	<string>Allow MicroPhone</string>
	<key>NSPhotoLibraryUsageDescription</key>
	<string>Allow Photos</string>
    <key>NSPhotoLibraryAddUsageDescription</key>
    <string>Allow write access</string>

Step 6: Logout User

Call the following when user logout from your app:

 if([ALUserDefaultsHandler isLoggedIn])
    {
        ALRegisterUserClientService *registerUserClientService = [[ALRegisterUserClientService alloc] init];
        [registerUserClientService logoutWithCompletionHandler:^(ALAPIResponse *response, NSError *error) {
            if(!error && [response.status isEqualToString:@"success"])
            {
                NSLog(@"Logout success");
            }
            else
            {
                NSLog(@"Logout failed with response : %@",response.response);
            }
        }];
    }

Swift

Download Chat SDK

ADD APPLOZIC FRAMEWORK

Download Applozic Chat latest framework here and add it to your project.

You can download Sample Chat app code (https://github.com/AppLozic/Applozic-iOS-Chat-Samples) sample project for more reference.

Add framework to your project:

i) Paste Applozic framework to root folder of your project.

ii) Go to Build Phase.

Expand Embedded frameworks and add applozic framework.

dashboard-blank-content

Login/Register User

Applozic will create a new user if the user doesn't exists. userId is the unique identifier for any user, it can be anything like email, phone number or uuid from your database.

i) Add Helper Classes:

Download ALChatManager.swift and add to your project.

ALChatManager.swift

ii) Add New cocoa class NSObject+ApplozicBridge in objective-c. On adding it will ask “would you like to create bridging header” say “yes” and in bridging file paste this code

#import "Applozic/ALMessage.h"
#import "Applozic/ALMessageClientService.h"
#import "Applozic/ALRegistrationResponse.h"
#import "Applozic/ALUser.h"
#import "Applozic/ALChatLauncher.h"
#import "Applozic/ALApplozicSettings.h"
#import "Applozic/ALAppLocalNotifications.h"
#import "Applozic/ALConversationService.h"

iii) Login/Register User:

At the top of your Swift source files, use import Applozic.

Convenient methods are present in ALChatManager.swift to register user with applozic. For simple user registration in background, you can use below method:

  let alUser : ALUser =  ALUser();
  alUser.applicationId = ALChatManager.applicationId
  alUser.userId = "demoUserId"       // NOTE : +,*,? are not allowed chars in userId.
  alUser.email = "[email protected]"
  alUser.imageLink = ""    // User's profile image link.
  alUser.displayName = "DemoUserName"  // User's Display Name
  
  ALUserDefaultsHandler.setUserId(alUser.userId)
  ALUserDefaultsHandler.setEmailId(alUser.email)
  ALUserDefaultsHandler.setDisplayName(alUser.displayName)
 func registerUser(alUser: ALUser, completion : (response: ALRegistrationResponse, error: NSError?) -> Void)

Initiate Chat

  1. Launch chat list screen:

    NOTE: Replace "applozic-sample-app" by your application key

    func registerUserAndLaunchChat(alUser:ALUser?, fromController:UIViewController,forUser:String?)

   //Example: 

        let chatManager : ALChatManager = ALChatManager(applicationKey: "applozic-sample-app")
        chatManager.registerUserAndLaunchChat(getUserDetail(), fromController: self, forUser:nil)
  1. Launch chat with specific user/group:
// Individual chat list launch for group or user with display name

 func launchChatForUser(forUserId : String ,fromViewController:UIViewController)

//Example:

        let chatManager : ALChatManager =  ALChatManager(applicationKey: "applozic-sample-app")
        chatManager.registerUserAndLaunchChat(getUserDetail(), fromController: self, forUser:"applozic")
  

Push Notification Setup

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. Sample code is as below:

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
    {
        print("DEVICE_TOKEN_DATA :: \(deviceToken.description)")  // (SWIFT = 3) : TOKEN PARSING

        var deviceTokenString: String = ""
        for i in 0..<deviceToken.count
        {
            deviceTokenString += String(format: "%02.2hhx", deviceToken[i] as CVarArg)
        }

        print("DEVICE_TOKEN_STRING :: \(deviceTokenString)")

        if (ALUserDefaultsHandler.getApnDeviceToken() != deviceTokenString)
        {
            let alRegisterUserClientService: ALRegisterUserClientService = ALRegisterUserClientService()
            alRegisterUserClientService.updateApnDeviceToken(withCompletion: deviceTokenString, withCompletion: { (response, error) in
                print ("REGISTRATION_RESPONSE :: \(response)")
            })
        }
    }
b) Receiving push notification :

Once your app receive notification, pass it to Applozic handler for chat notification processing.

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)
}                                                         
c) Handling app launch on notification click :
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

// Override point for customization after application launch.
let alApplocalNotificationHnadler : ALAppLocalNotifications =  ALAppLocalNotifications.appLocalNotificationHandler();
alApplocalNotificationHnadler.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
}                            

d) AppDelegate changes to observe background/foreground notification.
    func applicationDidEnterBackground(_ application: UIApplication) {

        print("APP_ENTER_IN_BACKGROUND")
        NotificationCenter.default.post(name: Notification.Name(rawValue: "APP_ENTER_IN_BACKGROUND"), object: nil)
    } ```
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

func applicationWillTerminate(application: UIApplication) {
    ALDBHandler.sharedInstance().saveContext()
}

##### f) APNs Certification Type Setup :

Upload your push notification certificate to Applozic Dashboard page under 'Edit Application' section in order to enable real time notification.
Applozic Dashboard -> Application -> Actions -> Edit -> Push Notification -> Upload APNS Certificate and password

In ALChatManager change setting according to your certificate and profile used:

Method Name:

ALDefaultChatViewSettings() -> Void

Code to set mode depending on your code signing and profile used:

For Development: ALUserDefaultsHandler.setDeviceApnsType(APNS_TYPE_DEVELOPMENT);

For Distribution: ALUserDefaultsHandler.setDeviceApnsType(APNS_TYPE_DISTRIBUTION);


#### Logout User

Call the following when user logout from your app:

let registerUserClientService: ALRegisterUserClientService = ALRegisterUserClientService() registerUserClientService.logout {

}