iOS SDK V2 - Reference

The Plivo iOS SDK allows you to create applications capable of making and receiving calls in your iOS app. This document gives an overview of different classes and methods available in Plivo iOS SDK v2.

iOS 14 Compatibility Notice: Plivo iOS SDK 2.1.17+ is fully compatible with iOS 14.
For more information, check here

Initialization of Application

Registering an endpoint

With options

The following code demonstrates registering an endpoint using a Plivo SIP URI & password with options.

let username = "Tatooine"
let password = "Jabba"
var endpoint: PlivoEndpoint = PlivoEndpoint(["debug":true,"enableTracking":true,"maxAverageBitrate":48000])

func login(withUserName userName: String, andPassword password: String) {
    endpoint.login(userName, andPassword: password)
}

Without options

The following code demonstrates registering an endpoint using a Plivo SIP URI & password without options.

let username = "Tatooine"
let password = "Jabba"
var endpoint: PlivoEndpoint = PlivoEndpoint()

func login(withUserName userName: String, andPassword password: String) {
    endpoint.login(userName, andPassword: password)
}

Access to Microphone

We have to provide Microphone access before making an outbound call or receiving an incoming call using AVFoundation

import AVFoundation

//Request Record permission
let session = AVAudioSession.sharedInstance()
if (session.responds(to: #selector(AVAudioSession.requestRecordPermission(_:)))) {
    AVAudioSession.sharedInstance().requestRecordPermission({(granted: Bool)-> Void in
        if granted {
            print("granted AVAudioSession permission")
            do {
                try session.setCategory(AVAudioSession.Category.playAndRecord, mode: .default, options: [])
                try session.setActive(true)
            }
            catch {
                print("Couldn't set Audio session category")
            }
        } else{
            print("not granted AVAudioSession permission")
        }
    })
}

Examples for basic call actions

Making an outbound call

The following code demonstrates making an outbound call from the SDK.

let toURI = "sip:Coruscant@phone.plivo.com"
var outgoing: PlivoOutgoing = endpoint.createOutgoingCall()
outgoing.call(toURI)

Receiving a call

The following code demonstrates receiving an incoming call in the SDK.

(void)onIncomingCall:(PlivoIncoming*)incoming
{
    *// Answer the call*
    [incoming answer];
}

Note: For more information on implementing incoming call in your iOS application, see the push notification section.

Classes and Methods

Class: PlivoEndpoint (PlivoEndpoint.h)

PlivoEndpoint (PlivoEndpoint.h) class allows you to register a Plivo SIP Endpoint. Once an endpoint is registered, you can make or receive calls using the endpoint. The following are the methods available in the PlivoEndpoint class.

Method 1: Registering an Endpoint

You can register an endpoint using:

  • Username, Password, Device Token and Certificate ID
  • Username, Password, and Device Token.
  • Username, Password, and Timeout.
  • Username and Password.

Registering an Endpoint- Using Username, Password, Device Token, and Certificate ID

Following are the parameters to be passed:

  • username: Username of the endpoint.
  • password: Password of the endpoint.
  • token: Device token for VOIP push notifications. Device token from APNS can be obtained by registering for Push Notifications.
  • certificateId: certificate Id created in plivo console. Manage Push credentials

If the endpoint is successfully registered, a notification is sent to the registerSuccess delegate. In case of a failure, a notification is sent to the registerFailure delegate.

(void)login:(NSString *)username AndPassword:(NSString *)password
DeviceToken:(NSData*)token CertificateId:(NSString*)certificateId;
Note: This is the recommended Login method to enable Incoming calls using Push Notifications.

USAGE

func login(withUserName userName: String, andPassword password: String, deviceToken token: Data,
  certificateId certificateId: String)
  {
    endpoint.login(userName, andPassword: password, deviceToken: token, certificateId: certificateId)
  }

Registering an Endpoint- Using Username, Password and Device Token

Following are the parameters to be passed:

  • username(username of the endpoint).
  • password(password of the endpoint).
  • token(device token for VOIP push notifications), Device token from APNS can be obtained by registering for Push Notifications.

If the endpoint is successfully registered a notification would be sent to the delegate registerSuccess. In case of a failure, a notification is sent to the delegate registerFailure.

(void)login:(NSString *)username AndPassword:(NSString *)password DeviceToken:(NSData*)token;

Usage

func login(withUserName userName: String, andPassword password: String, deviceToken token: Data) {
            endpoint.login(userName, andPassword: password, deviceToken: token)
        }

Registering an Endpoint- Using Username, Password, and Timeout

Following are the parameters to be passed:

  • username(username of the endpoint).
  • password(password of the endpoint).
  • regTimeout(Expiration time for registration in seconds).

If the endpoint is successfully registered a notification would be sent to the delegate registerSuccess. In case of a failure, a notification is sent to the delegate registerFailure.

(void)login:(NSString *)username AndPassword:(NSString *)password RegTimeout:(int)regTimeout;

Usage

func login(withUserName userName: String, andPassword password: String, withRegTimeout timeout: int) {
            endpoint.login(userName, andPassword: password, regTimeout: timeout)
        }

Registering an Endpoint- Using Username and Password

Following are the parameters to be passed:

  • username(username of the endpoint).
  • password(password of the endpoint).

If the endpoint is successfully registered, a notification will be sent to the registerSuccess delegate. In case of a failure, a notification is sent to the registerFailure delegate.

(void)login:(NSString*) username AndPassword:(NSString*) password;

Usage

func login(withUserName userName: String, andPassword password: String) {
    UtilClass.makeToastActivity()
    endpoint.login(userName, andPassword: password)
}

Method 2: Unregister an Endpoint

This method is used to unregister an endpoint.

(void)logout;

Method 3: Create Object for initiating Outbound calls

Calling this method returns a PlivoOutgoing object, linked to the registered endpoint. Calling this method on an unregistered PlivoEndpoint object returns an empty object.

(PlivoOutgoing*)createOutgoingCall;

Method 4: Submit call quality feedback

Following are the parameters to be passed:

  • callUUID - Mandatory string parameter used to identify the call the feedback belongs to. You can get the callUUID for last call using getLastCallUUID()
  • starRating - Mandatory integer parameter with a value from 1 to 5. For a score from 1 to 4, the issues parameter is mandatory and optional for a score of 5.
  • issues - IssueList is an Array and must have at least one of the following reasons listed below for starRating value from 1 to 4 - ‘AUDIO_LAG’, ‘BROKEN_AUDIO’, ‘CALL_DROPPPED’, ‘CALLERID_ISSUES’, ‘DIGITS_NOT_CAPTURED’, ‘ECHO’, ‘HIGH_CONNECT_TIME’, ‘LOW_AUDIO_LEVEL’, ‘ONE_WAY_AUDIO’, ‘ROBOTIC_AUDIO’, ‘OTHERS’
  • comments - Optional string attribute for users remarks, with a max length of 280 characters
  • sendConsoleLog - Boolean optional parameter with default value false. Set this to true to enable Plivo’s team to collect and analyze iOS SDK’s logs for a better understanding of the issue.

If the feedback is successfully submitted, a notification would be sent to the delegate “onFeedbackSuccess”. In case of any input validation error, a notification would be sent to the delegate “onFeedbackValidationError”. If the feedback submission fails, the “onFeedbackFailure” delegate is notified.

(void)submitCallQualityFeedback : (NSString *) callUUID : (NSInteger) startRating : (NSArray *) issues
: (NSString *) notes : (BOOL) sendConsoleLog;

Usage

func submitFeedback(starRating: Int , issueList: [AnyObject], comments: String, addConsoleLog: Bool) {
        let callUUID:String? = endpoint.getLastCallUUID();
        endpoint.submitCallQualityFeedback(callUUID, starRating,  issueList, notes, sendConsoleLog)
}

Method 5: Get call UUID

Returns a string call UUID if a call is active, else returns null.

(NSString *)getCallUUID

Usage

let callUUID:String? = endpoint.getCallUUID();

Method 6: Get last call UUID

Returns the call UUID of the latest answered call. Useful in the case if you want to send feedback for the last call.

(NSString *)getLastCallUUID

Usage

let callUUID:String? = endpoint.getLastCallUUID();

Class: PlivoOutgoing (PlivoOutgoing.h)

PlivoOutgoing class contains methods to make and control an outbound call.

Method 1: Initiate Outbound calls

Calling this method on the PlivoOutgoing object with the SIP URI would initiate an outbound call.

(void)call:(NSString *)sipURI error:(NSError **)error;

Method 2: Initiate Outbound calls with custom SIP headers

Calling this method on the PlivoOutgoing object with the SIP URI would initiate an outbound call with custom SIP headers.

(void)call:(NSString *)sipURI headers:(NSDictionary *)headers error:(NSError **)error;

Usage

func call(withDest dest: String, andHeaders headers: [AnyHashable: Any], error: inout NSError?) -> PlivoOutgoing {
    /* construct SIP URI , where kENDPOINTURL is a contant contaning domain name details*/
    let sipUri: String = "sip:\(dest)\(kENDPOINTURL)"
    /* create PlivoOutgoing object */
    outCall = (endpoint.createOutgoingCall())!
    /* do the call */
    outCall?.call(sipUri, headers: headers, error: &error)
    return outCall!
}

//To Configure Audio
func configureAudioSession() {
    endpoint.configureAudioDevice()
}

Method 3: Mute a call

Calling this method on the PlivoOutgoing object mutes the call.

(void)mute;

Usage

func onIncomingCall(_ incoming: PlivoIncoming) {
..

// assign incCall var
 incCall = incoming
}
// to mute incoming call
if (incCall != nil) {
 incCall?.mute()
 }

Method 4: Unmute a call

Calling this method on the PlivoOutgoing object unmutes the call.

(void)unmute;

Usage

if (incCall != nil) {
 incCall?.unmute()
}

Method 5: Send Digits

Calling this method on the PlivoOutgoing object with the digits sends DTMF on that call. DTMF input only supports 0-9 , *, and #.

(void)sendDigits:(NSString*)digits;

Usage

func getDtmfText(_ dtmfText: String) {
    if (incCall != nil) {
        incCall?.sendDigits(dtmfText)
        ..
    }
}

Method 6: Hangup a call

Calling this method on the PlivoOutgoing object would hang up the call.

(void)hangup;

Usage

if (self.incCall != nil) {
    print("Incoming call - Hangup");
    self.incCall?.hangup()
    self.incCall = nil
}

Method 7: Hold a call

Calling this method on the PlivoOutgoing object disconnects the audio devices during an audio interruption.

(void)hold;

Usage

if (incCall != nil) {
    incCall?.hold()
}
if (outCall != nil) {
    outCall?.hold()
}
Phone.sharedInstance.stopAudioDevice()

Method 8: Unhold a call

Calling this method on the PlivoOutgoing object reconnects the audio devices after an audio interruption.

(void)unhold;

Description

Usage

if (incCall != nil) {
     incCall?.unhold()
}
if (outCall != nil) {
     outCall?.unhold()
}
Phone.sharedInstance.startAudioDevice()

Class: PlivoIncoming(PlivoIncoming.h)

PlivoIncoming class contains methods to handle the incoming call. An object of this class will be received on the following delegate.

(void)incomingCall:(PlivoIncoming*) incoming;

Method 1: Answer an Incoming call

Calling this method on the PlivoIncoming object answers the call.

(void)answer;

Usage

func provider(_ provider: CXProvider, perform action: CXAnswerCallAction) {
  //Answer the call
   incCall?.answer()
  outCall = nil
  action.fulfill()

Method 2: Reject an Incoming call

Calling this method on the PlivoIncoming object rejects the call.

(void)reject;

Usage

if (self.incCall != nil) {
    print("Incoming call - Reject");
    self.incCall?.reject()
    self.incCall = nil
}

Configuration Parameters

The following are the configuration parameters:

Attribute Description Allowed Values Default Value
debug Enable log messages true/false false
enableTracking Set to true if you want to get mediaMetrics events and enable call quality tracking. true/false true
maxAverageBitrate

This param may be used to control your application’s bandwidth consumption for calls.

A higher maxAverageBitrate value may result in more bandwidth consumption, but also better audio quality.

Lowering the maxAverageBitrate impacts call quality as the audio is compressed to a greater extent to reduce bandwidth consumption.

This param only applies to calls using Opus codec. Check out RFC-7587 section 7.1 for more info.

8000 - 48000 48000

PlivoEndpoint Delegates

Delegate 1: On Login

Delegate

(void)onLogin;

Description When registration to an endpoint is successful.

Parameters Error details

Return Value None

Delegate 2: Handling Login Failure

Delegate

(void)onLoginFailure;

Description This delegate gets called when registration to an endpoint fails.

Parameters None

Return Value None

Delegate 3: Handling Login Failure with Errors

Delegate

(void)onLoginFailedWithError:(NSError *)error;

Description This delegate gets called when registration to an endpoint fails.

Parameters Error details

Return Value None

Delegate 4: On Incoming Call

Delegate

(void)onIncomingCall:(PlivoIncoming*)incoming;

Description This delegate gets called when there is an incoming call to a registered endpoint

Parameters Incoming object

Return Value None

Delegate 5: On Incoming Call Rejected

Delegate

(void)onIncomingCallRejected:(PlivoIncoming*)incoming;

Description On an incoming call, if the call is disconnected by the caller, this delegate would be triggered with the PlivoIncoming object.

Parameters Incoming object

Return Value None

Delegate 6: On Incoming Call Hangup

Delegate

(void)onIncomingCallHangup:(PlivoIncoming*)incoming;

Description On an incoming call, if the call is disconnected by the caller after being answered, this delegate would be triggered with the PlivoIncoming object.

Parameters Incoming object

Return Value None

Delegate 7: On Incoming Digit

Delegate

(void)onIncomingDigit:(NSString*)digit;

Description On an active endpoint, this delegate would be called with the digit received on the call.

Parameters String for DTMF digit

Return Value None

Delegate 8: On Incoming Call Answered

Delegate

(void)onIncomingCallAnswered:(PlivoIncoming*)incoming;

Description This delegate gets called when the incoming call is answered and audio is ready to flow.

Parameters Incoming object

Return Value None

Delegate 9: On Incoming Call Invalid

Delegate

(void)onIncomingCallInvalid:(PlivoIncoming*)incoming;

Description For an incoming call, this delegate gets called when the callee does not accept or reject the call in 40 seconds or SDK is not able to establish a connection with Plivo.

Parameters Incoming object

Return Value None

Delegate 10: On Calling

Delegate

(void)onCalling:(PlivoOutgoing*)call;

Description When an outgoing call is initiated, this delegate would be called with the PlivoOutgoing object.

Parameters Outgoing object

Return Value None

Delegate 11: On Outgoing Call Ringing

Delegate

(void)onOutgoingCallRinging:(PlivoOutgoing*)call;

Description When an outgoing call is ringing, this delegate would be called with the PlivoOutgoing object.

Parameters Outgoing object

Return Value None

Delegate 12: On Outgoing Call Answer

Delegate

(void)onOutgoingCallAnswered:(PlivoOutgoing*)call;

Description When an outgoing call is answered, this delegate would be called with the PlivoOutgoing object.

Parameters Outgoing object

Return Value None

Delegate 13: On Outgoing Call Rejected

Delegate

(void)onOutgoingCallRejected:(PlivoOutgoing*)call;

Description When an outgoing call is rejected by the called number, this delegate would be called with the PlivoOutgoing object.

Parameters Outgoing object

Return Value None

Delegate 14: On Outgoing Call Hangup

Delegate

(void)onOutgoingCallHangup:(PlivoOutgoing*)call;

Description When an outgoing call is disconnected by the called number after the call has been answered.

Parameters Outgoing object

Return Value None

Delegate 15: On Outgoing Call Invalid

Delegate

(void)onOutgoingCallInvalid:(PlivoOutgoing*)call;

Description When an outgoing call is made to an invalid number, this delegate would be called with the PlivoOutgoing object.

Parameters Outgoing object

Return Value None

Delegate 16: MEDIA METRICS

Description For an ongoing call, if any of the below events are triggered, the mediaMetrics delegate will be called with respective values of the event in the mediaMetrics object.

Parameters mediaMetrics object

Return Value None

Events Description Example
high_jitter when the jitter is higher than 30 ms for 2 out of the last 3 samples.

This event will be generated individually for the local stream and remote stream.

{ group: ‘network’, level: ‘warning’, type: ‘high_jitter’, active: true/false, // false when the value goes to normal level (last 2 out of 3 samples have jitter less than 30 ms) value: ‘<average jitter value>’, desc: ‘high jitter detected due to network congestion, can result in audio quality problems’, stream: ‘local || remote’ }
high_rtt When the RTT is higher than 400 ms for 2 out of the last 3 samples { group: ‘network’, level: ‘warning’, type: ‘high_rtt’, active: true/false, // false when value goes to normal level (last 2 out of 3 samples have RTT less than 400 ms) value: ‘<average rtt value>’, desc: ‘high latency detected, can result in delay in audio’, stream: ‘None’ }
high_packetloss When the packet loss is > 10% for OPUS and loss > 2% PCMU.

This event will be generated individually for the local stream and remote stream.

{ group: ‘network’, level: ‘warning’, type: ‘high_packetloss’, active: true/false, // false when value goes to normal level value: ‘<average packet loss value>’, desc: ‘high packet loss is detected on media stream, can result in choppy audio or dropped call’, stream: ‘local || remote’ }
low_mos When sampled mos is < 3.5 for 2 out of the last 3 samples. { group: ‘network’, level: ‘warning’, type: ‘low_mos’, active: true/false, // false when value goes to normal level. value: ‘<current_mos_value>’, desc: ‘low Mean Opinion Score (MOS)’, stream: ‘None’ }
no_audio_received When remote or local audio is silent

This event will be generated individually for the local stream and remote stream.

{ group: ‘audio’, level: ‘warning’, type: ‘no_audio_received’, active: true/false, // false when value goes to normal level value: ‘<current_value_in_dB>’, desc: ‘no audio packets received’ stream: ‘local || remote’ }

Receiving Incoming SIP Headers

You can receive custom SIP headers on an incoming call as a part of the PlivoIncoming object on the ‘onIncomingCall’ delegate. For example:

(void)onIncomingCall:(PlivoIncoming*)incoming
{
    if ([incoming.extraHeaders count] > 0) {
        NSLog(@"-- Incoming call extra headers --");
        for (NSString *key in incoming.extraHeaders) {
            NSString *value = [incoming.extraHeaders objectForKey:key];
            NSLog(@"%@ => %@", key, value);
        }
    }
    *// Answer the call here.*
}

Resetting your Endpoint

If you choose to manually reset your endpoints and disable their WebSocket transport, you can use the resetEndpoint method as shown below:

[PlivoEndpoint resetEndpoint];
 self.endpoint = [[PlivoEndpoint alloc] init];

Please ensure that you initialize the endpoint after reset, as shown above, otherwise, WebSocket transport will not be re-initialized and your application will not be able to communicate with Plivo servers.

Methods supporting Pushkit and Callkit in PlivoEndpoint

APIs for pushkit Integration

Method 1: Register Token

This method is used to register the device token for VOIP push notifications.

(void)registerToken:(NSData*)token;

Method 2: Relay Push Notification

pushInfo is the NSDictionary object forwarded by the apple push notification.

(void)relayVoipPushNotification:(NSDictionary *)pushInfo;

Usage

func pushRegistry(_ registry: PKPushRegistry, didReceiveIncomingPushWith payload: PKPushPayload, forType type: PKPushType)
{          
    Phone.sharedInstance.relayVoipPushNotification(payload.dictionaryPayload)
    payload.dictionaryPayload contains below info:
    {
        alert = "plivo";
        callid = "ABC-456-DEF-789-GHI";
        sound = default;
    }
    Pass the payload.dictionaryPayload to relayVoipPushNotification API and then you will receive incoming calls the same way.
}

APIs for Callkit Integration

The following are the three APIs that are required for Apple Callkit integration.

Method 1: Configure Audio Session

This method is used to Configure audio session before the call.

(void)configureAudioSession

Method 2: Start Audio Device

Depending on the call status (Hold or Active) you’ll want to start or stop processing the call’s audio. Use this method to signal the SDK to start audio I/O units when receiving the audio activation callback from CallKit.

(void)startAudioDevice

Method 3: Stop Audio Device

Depending on the call status(Hold or Active) you’ll want to start, or stop processing the call’s audio, use this method to signal the SDK to stop audio I/O units when receiving deactivation or reset callbacks from CallKit

(void)configureAudioSession

Usage

To Configure Audio

func configureAudioSession() {

    endpoint.configureAudioDevice()

}

Start the Audio service to handle audio interruptions use AVAudioSessionInterruptionTypeBegan and AVAudioSessionInterruptionTypeEnded.

func startAudioDevice() {
    endpoint.startAudioDevice()
}
func stopAudioDevice() {
    endpoint.stopAudioDevice()
}

To turn on the speakers

do {
    try audioSession.overrideOutputAudioPort(AVAudioSessionPortOverride.speaker)
} catch let error as NSError {
    print("audioSession error: \(error.localizedDescription)")
}

To turn off the speakers

set AVAudioSessionPortOverride:none