Introduction

Applozic’s iOS Audio and Video Call SDK provides you with all the necessary components to build a real time chat with voice and video capabilities within your application, and enables you as a developer to implement conversational chatpush notificationsgroup chat, picture in picture and many more such features!

One of the worldwide effects of Covid-19 and the resulting governmental lockdowns was the acute rise in the need for real time communication across multiple industries. A few major ones, like healthcare, education, and technology support witnessed the birth and rapid growth of first to market applications that catered to the varied needs of the customer. For example, the features offered in telemedicine caused much needed disruption in a field with vital importance on immediate communication.

In this article, we will leverage the Applozic iOS Voice and Video SDK to create a real time chat application that can be used across industries like real time customer support, 1 on 1 telemedicine, personal therapy, etc. With HIPAA compliant security on all your conversations and programmable personalization capabilities to improve customer experiences, Applozic enables you to drive better engagement, increase interactions with your users, and improve your chances of retaining those customers through high-quality video and audio.

Creating your own real time communication app

Applozic Audio-Video Call SDK provides high-quality IP audio and video calls capabilities within your application. With this SDK, your application’s users can take part in secure 1-to-1 calls and automate workflows by building reliable conversation systems through voice-calling and video-calling. You can create a standalone application for communication using this SDK, or integrate it with your existing application.

Note: The Voice and Video SDK is a beta product and new features will be added in the upcoming months.

If you face any difficulties while following this tutorial, you can contact us at support@applozic.com.
To check out our cocoapods sample app, click here.

Requirements

Here are some of the dependencies you will need:

  • Xcode 12.0 or later
  • CocoaPods 1.9.0 or later
  • Your project must target iOS 11 or higher

Note: We are assuming the following application is going to be written using Objective-C. For corresponding code in Swift, please check the documentation linked within each section.

Application Setup

To use the Applozic  iOS Audio Video SDK and leverage pre-built components that you can easily customize, you can sign up for Applozic and get your APP_ID from the install section of the console.

Installation – Setup the building blocks for audio and video capabilities

Cocoapods

  • ApplozicAudioVideo is available through CocoaPods.
  • To install it, setup your Podfile located at /ios/Podfile and add below pod dependency:
source 'https://github.com/CocoaPods/Specs'
use_frameworks!  # Required to add 
platform :ios, '11.0' # Required to add

target 'TARGET_NAME' do
    pod 'ApplozicAudioVideo'  # Required to add 
end
  • Navigate to YourApp/ios directory from terminal and run the below command:
pod install
Note:  If you do not have pod dependency, check out how to get started here.

The Audio-Video Call SDK includes our iOS messaging SDK. If you have added the pod ‘Applozic’ in your Podfile please remove that and replace it with ‘ApplozicAudioVideo’.

Add Permissions

Add permissions for Camera, Photo Library, Microphone, Contacts and Location usage.

Note: We won't be asking the users for these permissions unless they use the respective feature. Due to Apple's requirement, we have to add these permissions if we are using any of their APIs related to Camera, Microphone, etc.

Open Info.plist from /ios/YOUR_PROJECT_NAME/Info.plist file and paste these permissions anywhere inside the <dict> tag.

<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>

Setup Application ID

At this step, you should already have signed up for Applozic and obtained your APP_ID.

Open the ALChatManager.h file and replace “applozic-sample-app” with your APP-ID.

#define APPLICATION_ID @"<YOUR_APPLOZIC_APP_ID>"

Once you are at this stage, follow the Applozic documentation to complete the authentication, set up of user profiles and other such basic building blocks of your application.

Integration – Authenticate and set up push notification

Authentication

Authentication serves two purposes here:

  1. It helps you to identify users i.e. differentiate between the users who have access to real time chat from those who do not have access to chat.
  2. It enables you to set up user profiles necessary for real time communication.

We have a detailed guide on setting up authentication for your application in our documentation. Once you have completed the steps, we can move on to the next stage.

Add Audio video configuration

Add below lines of code in ALChatManger.m’s file in the method ALDefaultChatViewSettings to enable the audio-video call capabilities.

[ALApplozicSettings setAudioVideoClassName:@"ALAudioVideoCallVC"]; [ALApplozicSettings setAudioVideoEnabled:YES];

Push Notification Setup

There are two types of push notifications that need to be set up at this stage.

  • Apple Push Notification service (APNs) certificate, which enables you to send push notifications to your user’s device.
  • VOIP certificate, which is required for sending incoming call notification from applozic to your app

Setting up APNs Certificates

Applozic sends the communication payload to Apple servers, which then sends the push notification to your user’s device.

Creating APNs certificates

For Apple to send push notifications to user devices, you need to create an APNs certificate in your Apple developer account.

  1. Visit this link, to create Apple Push Notification service SSL (Sandbox) i.e development certificate.
  2. Visit this link, to create Apple Push Notification service SSL (Sandbox & Production), i.e, distribution certificate.

Note: Supported format for APNs certificate is .p12

Once the certificates are created you can download them and export the p12 files with password for development and distribution certificate using Keychain Access in Mac.

Upload APNs Certificates

Go to Applozic console push notification section to upload the APNs development and distribution certificates. The following screenshot is what will be visible on the console for you:

apns certificate upload in applozic console

Updating capabilities and customizing Chat UI

Applozic documentation has a detailed guide to understand how to setup your text push notification capabilities and customize the UI from either a pre-built model or create your own UI from scratch.

Follow the mentioned guides and that will bring us to the next stage of creating and setting up the VOIP certificates.

Setting up VOIP certificate

Creating and adding your VOIP certificate

VOIP certificate is required for sending incoming call notification from Applozic to your app

  1. Visit your Apple developer account, and create a VoIP Services Certificate. It should look like this:
VOIP-certificate

Once the certificate is created in developer console,

  • Download the certificate and export the p12 file with password from the downloaded certificate using Keychain Access in Mac.
  • Contact support@applozic.com via email for uploading this VOIP certificate as we dont have the option to upload this from the Applozic console right now.
Note: You will need to send an email to support@applozic.com with your Applozic APP-ID and p12 VOIP certificate and password for uploading the p12 VOIP certificate as we don't have the option to upload this from the Applozic console right now.

Configuring Your App

Adding Capabilities to Your App

The next step is to set up capabilities to configure app services from Apple, such as push notifications, background modes, VOIP, etc.

  • On the Xcode project’s Signing & Capabilities tab, Click (+ Capability) to add “Push Notifications”.
  • Next Click (+ Capability) to add “Background modes” enable the following four options from Background Modes:
    • Audio, AirPlay and Picture in Picture
    • Voice over IP
    • Background fetch
    • Remote notifications

Your screen should look like the following screenshot:

screen after setting up capabilities

Configure the push notification in the Appdelegate file of your project

NOTE: Without push notifications set-up, calls won't work as call notification requires a VOIP notification. Please make sure the push notifications are set-up properly.

Add the below imports in the Appdelegate file:

#import <Applozic/Applozic.h>
#import <UserNotifications/UserNotifications.h>
#import <PushKit/PushKit.h>
#import <ApplozicAudioVideo/ALAudioVideoPushNotificationService.h>
#import <ApplozicAudioVideo/ALAudioVideoCallHandler.h>

Ensure that your Appdelegate has these imports:

@interface AppDelegate () <UNUserNotificationCenterDelegate, PKPushRegistryDelegate>

Register PushRegistry for VOIP notification

The below code can be used to register the push notifications.
If you have added the method registerForNotification from the basic notification setup then you can replace it with the below registerForNotification method code.

// Register APNs and Pushkit 
-(void)registerForNotification
{
    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." );
                
                /// Push kit Registry
                PKPushRegistry * pushKitVOIP = [[PKPushRegistry alloc] initWithQueue:dispatch_get_main_queue()];
                pushKitVOIP.desiredPushTypes = [NSSet setWithObject:PKPushTypeVoIP];
                pushKitVOIP.delegate = self;
            });
        }
        else
        {
            NSLog(@"Push registration FAILED" );
            NSLog(@"ERROR: %@ - %@", error.localizedFailureReason, error.localizedDescription );
            NSLog(@"SUGGESTIONS: %@ - %@", error.localizedRecoveryOptions, error.localizedRecoverySuggestion );
        }
    }];
}

Add the notification handler for VOIP

In your Appdelegate file find the method didFinishLaunchingWithOptions and add the below code just below the ALAppLocalNotifications handler:

[[ALAudioVideoCallHandler shared] dataConnectionNotificationHandler];

Sending an APNs and VOIP device token to Applozic server

The below code will enable you to send the APNs and VOIP device token to Applozic server.
If you added the code from the basic push notification setup before for didRegisterForRemoteNotificationsWithDeviceToken you will need to remove that and add the following code:

// APNs device token sending to applozic
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSLog(@"DEVICE_TOKEN :: %@", 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(@"APN_DEVICE_TOKEN :: %@", hexToken);

    if ([[ALUserDefaultsHandler getApnDeviceToken] isEqualToString:apnDeviceToken]) {
        return;
    }

    ALRegisterUserClientService *registerUserClientService = [[ALRegisterUserClientService alloc] init];
    [registerUserClientService updateAPNsOrVOIPDeviceToken:apnDeviceToken
                                          withApnTokenFlag:YES withCompletion:^(ALRegistrationResponse *response, NSError *error) {

    }];
}

// Pushkit VOIP token sending to applozic 
-(void)pushRegistry:(PKPushRegistry *)registry didUpdatePushCredentials:(PKPushCredentials *)credentials forType:(PKPushType)type {

    NSLog(@"PUSHKIT : VOIP_TOKEN_DATA : %@",credentials.token);
    const unsigned *tokenBytes = [credentials.token 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])];

    NSLog(@"PUSHKIT : VOIP_TOKEN : %@",hexToken);
    if ([[ALUserDefaultsHandler getVOIPDeviceToken] isEqualToString:hexToken]) {
        return;
    }

    NSLog(@"PUSHKIT : VOIP_TOKEN_UPDATE_CALL");
    ALRegisterUserClientService *registerUserClientService = [[ALRegisterUserClientService alloc] init];
    [registerUserClientService updateAPNsOrVOIPDeviceToken:hexToken
                                          withApnTokenFlag:NO withCompletion:^(ALRegistrationResponse *response, NSError *error) {

    }];
}

Receiving push notification

Once your app receives notification, you need to pass it to the Applozic handler for chat notification processing.

If you have added the didReceiveRemoteNotification UIBackgroundFetchResult method from the basic push notification please remove that UIBackgroundFetchResult method and replace it with the below code in the Appdelegate file:

-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler{

    NSLog(@"RECEIVED_NOTIFICATION_WITH_COMPLETION :: %@", userInfo);
    ALPushNotificationService *pushNotificationService = [[ALPushNotificationService alloc] init];
    if ([pushNotificationService isApplozicNotification:userInfo]) {
        ALAudioVideoPushNotificationService * audioVideoPushNotificationService = [[ALAudioVideoPushNotificationService alloc] init];
        [audioVideoPushNotificationService processPushNotification:userInfo];
        [pushNotificationService notificationArrivedToApplication:application withDictionary:userInfo];
        completionHandler(UIBackgroundFetchResultNewData);
        return;
    }
    completionHandler(UIBackgroundFetchResultNewData);
}

// PushKit delegate for VOIP call notification 
- (void)pushRegistry:(PKPushRegistry *)registry didReceiveIncomingPushWithPayload:(PKPushPayload *)payload forType:(PKPushType)type withCompletionHandler:(void(^)(void))completion {

    NSLog(@"PUSHKIT : INCOMING VOIP NOTIFICATION : %@", payload.dictionaryPayload.description);

    ALAudioVideoPushNotificationService *pushNotificationService = [[ALAudioVideoPushNotificationService alloc] init];
    NSDictionary * userInfoPayload = payload.dictionaryPayload;
    if ([pushNotificationService isApplozicNotification:userInfoPayload]) {
        [pushNotificationService processPushNotification:userInfoPayload];
        completion();
        return;
    }
    completion();
}

Conclusion

We began this article by discussing the essential need behind enabling real time communication in your application with voice and video capabilities. A few key features that we wanted to implement were secure 1 to 1 voice and video calls, push notifications and capability to integrate these with your existing application.

In order to implement these features, first we began by installing the building blocks for audio and video capabilities and set up your application with the required permissions.

Next, we integrated a few critical development blocks by setting up authentication and push notification services.

Finally, we have walked through the configuration pieces of the capabilities that can be added to your application and explained how we can customize them as well.

As we end this tutorial, you should be all set to continue experimentation with your application and add more features like rich messaging, multi-format attachments, etc.

Let us know in the comments if you would like to see a follow-up blog where we continue to add more features as we develop them, and feel free to leave any feedback as well!

Author

Anurag is a Technical Writer and technology enthusiast who enjoys science fiction and PC gaming.