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
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)
}
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)
}
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")
}
})
}
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)
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.
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.
You can register an endpoint using:
Following are the parameters to be passed:
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;
USAGE
func login(withUserName userName: String, andPassword password: String, deviceToken token: Data,
certificateId certificateId: String)
{
endpoint.login(userName, andPassword: password, deviceToken: token, certificateId: certificateId)
}
Following are the parameters to be passed:
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;
func login(withUserName userName: String, andPassword password: String, deviceToken token: Data) {
endpoint.login(userName, andPassword: password, deviceToken: token)
}
Following are the parameters to be passed:
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;
func login(withUserName userName: String, andPassword password: String, withRegTimeout timeout: int) {
endpoint.login(userName, andPassword: password, regTimeout: timeout)
}
Following are the parameters to be passed:
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;
func login(withUserName userName: String, andPassword password: String) {
UtilClass.makeToastActivity()
endpoint.login(userName, andPassword: password)
}
This method is used to unregister an endpoint.
(void)logout;
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;
Following are the parameters to be passed:
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;
func submitFeedback(starRating: Int , issueList: [AnyObject], comments: String, addConsoleLog: Bool) {
let callUUID:String? = endpoint.getLastCallUUID();
endpoint.submitCallQualityFeedback(callUUID, starRating, issueList, notes, sendConsoleLog)
}
Returns a string call UUID if a call is active, else returns null.
(NSString *)getCallUUID
let callUUID:String? = endpoint.getCallUUID();
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
let callUUID:String? = endpoint.getLastCallUUID();
PlivoOutgoing class contains methods to make and control an outbound call.
Calling this method on the PlivoOutgoing object with the SIP URI would initiate an outbound call.
(void)call:(NSString *)sipURI error:(NSError **)error;
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;
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()
}
Calling this method on the PlivoOutgoing object mutes the call.
(void)mute;
func onIncomingCall(_ incoming: PlivoIncoming) {
..
// assign incCall var
incCall = incoming
}
// to mute incoming call
if (incCall != nil) {
incCall?.mute()
}
Calling this method on the PlivoOutgoing object unmutes the call.
(void)unmute;
if (incCall != nil) {
incCall?.unmute()
}
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;
func getDtmfText(_ dtmfText: String) {
if (incCall != nil) {
incCall?.sendDigits(dtmfText)
..
}
}
Calling this method on the PlivoOutgoing object would hang up the call.
(void)hangup;
if (self.incCall != nil) {
print("Incoming call - Hangup");
self.incCall?.hangup()
self.incCall = nil
}
Calling this method on the PlivoOutgoing object disconnects the audio devices during an audio interruption.
(void)hold;
if (incCall != nil) {
incCall?.hold()
}
if (outCall != nil) {
outCall?.hold()
}
Phone.sharedInstance.stopAudioDevice()
Calling this method on the PlivoOutgoing object reconnects the audio devices after an audio interruption.
(void)unhold;
if (incCall != nil) {
incCall?.unhold()
}
if (outCall != nil) {
outCall?.unhold()
}
Phone.sharedInstance.startAudioDevice()
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;
Calling this method on the PlivoIncoming object answers the call.
(void)answer;
func provider(_ provider: CXProvider, perform action: CXAnswerCallAction) {
//Answer the call
incCall?.answer()
outCall = nil
action.fulfill()
Calling this method on the PlivoIncoming object rejects the call.
(void)reject;
if (self.incCall != nil) {
print("Incoming call - Reject");
self.incCall?.reject()
self.incCall = nil
}
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 |
Delegate
(void)onLogin;
Description When registration to an endpoint is successful.
Parameters Error details
Return Value None
Delegate
(void)onLoginFailure;
Description This delegate gets called when registration to an endpoint fails.
Parameters None
Return Value None
Delegate
(void)onLoginFailedWithError:(NSError *)error;
Description This delegate gets called when registration to an endpoint fails.
Parameters Error details
Return Value None
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
(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
(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
(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
(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
(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
(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
(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
(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
(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
(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
(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
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’
}
|
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.*
}
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.
This method is used to register the device token for VOIP push notifications.
(void)registerToken:(NSData*)token;
pushInfo is the NSDictionary object forwarded by the apple push notification.
(void)relayVoipPushNotification:(NSDictionary *)pushInfo;
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.
}
The following are the three APIs that are required for Apple Callkit integration.
This method is used to Configure audio session before the call.
(void)configureAudioSession
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
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
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