TwilioVoice Class Reference

Inherits from NSObject
Declared in TwilioVoice.h

Overview

TwilioVoice is the entry point to the Twilio Voice SDK. You can register for VoIP push notifications, make outgoing Calls, receive Call invites and set audio device to use in a Call using this class.

CallKit Audio Session Handling

Other Methods

  logLevel

The current logging level used by the SDK.

@property (nonatomic, assign, class) TVOLogLevel logLevel

Discussion

The default logging level is TVOLogLevelError. TwilioVoice and its components use NSLog internally.

See Also

Declared In

TwilioVoice.h

  audioDevice

The TVOAudioDevice used to record and playback audio in a Call.

@property (class, nonatomic, strong, nonnull) id<TVOAudioDevice> audioDevice

Discussion

If you wish to provide your own TVOAudioDevice then you must set it before performing any other actions with the SDK like connecting to a Call. It is also possible to change the device when you are no longer connected to any Calls and have destroyed all other SDK objects.

See Also

Declared In

TwilioVoice.h

+ sdkVersion

Returns the version of the SDK.

+ (nonnull NSString *)sdkVersion

Return Value

The version of the SDK.

Declared In

TwilioVoice.h

+ setLogLevel:module:

Sets the logging level for an individual module.

+ (void)setLogLevel:(TVOLogLevel)logLevel module:(TVOLogModule)module

Parameters

logLevel

The TVOLogLevel level to be used by the module.

module

The TVOLogModule for which the logging level is to be set.

Declared In

TwilioVoice.h

+ logLevelForModule:

Retrieve the log level for a specific module in the TwilioVoice SDK.

+ (TVOLogLevel)logLevelForModule:(TVOLogModule)module

Parameters

module

The TVOLogModule for which the log level needs to be set.

Return Value

The current log level for the specified module.

Declared In

TwilioVoice.h

Managing VoIP Push Notifications

+ registerWithAccessToken:deviceToken:completion:

Registers for Twilio VoIP push notifications.

+ (void)registerWithAccessToken:(nonnull NSString *)accessToken deviceToken:(nonnull NSString *)deviceToken completion:(nullable void ( ^ ) ( NSError *__nullable error ))completion

Parameters

accessToken

Twilio Access Token.

deviceToken

The push registry token for Apple VoIP Service.

completion

Callback block to receive the result of the registration.

Discussion

Registering for push notifications is required to receive incoming call notification messages through Twilio’s infrastructure. Once successfully registered, the registered binding has a time-to-live(TTL) of 1 year. If the registered binding is inactive for 1 year it is deleted and push notifications to the registered identity will not succeed. However, whenever the registered binding is used to reach the registered identity the TTL is reset to 1 year. A successful registration will ensure that push notifications will arrive via the APNs for the lifetime of the registration device token provided by the APNs instance.

The identity provided in the Access Token may only contain alpha-numeric and underscore characters. Other characters, including spaces, will result in undefined behavior.

If the registration is successful the completion handler will contain a Null NSError. If the registration fails, the completion handler will have a nonnull NSError with UserInfo string describing the reason for failure.

Registration ErrorError CodeDescription
TVOErrorAccessTokenInvalidError 20101Twilio was unable to validate your Access Token
TVOErrorAccessTokenHeaderInvalidError 20102Invalid Access Token header
TVOErrorAccessTokenIssuerInvalidError 20103Invalid Access Token issuer or subject
TVOErrorAccessTokenExpiredError 20104Access Token has expired or expiration date is invalid
TVOErrorAccessTokenNotYetValidError 20105Access Token not yet valid
TVOErrorAccessTokenGrantsInvalidError 20106Invalid Access Token grants
TVOErrorExpirationTimeExceedsMaxTimeAllowedError 20157Expiration Time in the Access Token Exceeds Maximum Time Allowed
TVOErrorAccessForbiddenError 20403Forbidden. The account lacks permission to access the Twilio API
TVOErrorBadRequestError 31400Bad Request. The request could not be understood due to malformed syntax
TVOErrorForbiddenError 31403Forbidden. The server understood the request, but is refusing to fulfill it
TVOErrorNotFoundError 31404Not Found. The server has not found anything matching the request
TVOErrorRequestTimeoutError 31408Request Timeout. A request timeout occurred
TVOErrorConflictError 31409Conflict. The request could not be processed because of a conflict in the current state of the resource. Another request may be in progress
TVOErrorUpgradeRequiredError 31426Upgrade Required. The client should switch to a different protocol
TVOErrorTooManyRequestsError 31429Too Many Requests. Too many requests were sent in a given amount of time
TVOErrorInternalServerError 31500Internal Server Error. The server could not fulfill the request due to some unexpected condition
TVOErrorBadGatewayError 31502Bad Gateway. The server is acting as a gateway or proxy, and received an invalid response from a downstream server while attempting to fulfill the request
TVOErrorServiceUnavailableError 31503Service Unavailable. The server is currently unable to handle the request due to a temporary overloading or maintenance of the server
TVOErrorGatewayTimeoutError 31504Gateway Timeout. The server, while acting as a gateway or proxy, did not receive a timely response from an upstream server
TVOErrorTokenAuthenticationRejected 51007Token authentication is rejected by authentication service
TVOErrorRegistrationError 31301Registration failed. Look at [error localizedFailureReason] for details

Insights

Group NameEvent NameDescriptionSince version
registrationregistrationRegistration is successful3.0.0-beta3
registration registration-errorRegistration failed3.0.0-beta3

An example of using the registration API

[TwilioVoice registerWithAccessToken:accessToken
    deviceToken:deviceToken
    completion:^(NSError *error) {
        if(error != nil) {
            NSLog("Failed to register for incoming push: %@\n\t  - reason: %@", [error localizedDescription], [error localizedFailureReason]);
        } else {
            NSLog("Registration successful");
        }
}];

Declared In

TwilioVoice.h

+ unregisterWithAccessToken:deviceToken:completion:

Unregisters from Twilio VoIP push notifications.

+ (void)unregisterWithAccessToken:(nonnull NSString *)accessToken deviceToken:(nonnull NSString *)deviceToken completion:(nullable void ( ^ ) ( NSError *__nullable error ))completion

Parameters

accessToken

Twilio Access Token.

deviceToken

The push registry token for Apple VoIP Service.

completion

Callback block to receive the result of the unregistration.

Discussion

Call this method when you no longer want to receive push notifications for incoming Calls.

The identity provided in the Access Token may only contain alpha-numeric and underscore characters. Other characters, including spaces, will result in undefined behavior.

If the unregistration is successful the completion handler will contain a Null NSError. If the unregistration fails, the completion handler will have a nonnull NSError with UserInfo string describing the reason for failure.

Registration ErrorError CodeDescription
TVOErrorAccessTokenInvalidError 20101Twilio was unable to validate your Access Token
TVOErrorAccessTokenHeaderInvalidError 20102Invalid Access Token header
TVOErrorAccessTokenIssuerInvalidError 20103Invalid Access Token issuer or subject
TVOErrorAccessTokenExpiredError 20104Access Token has expired or expiration date is invalid
TVOErrorAccessTokenNotYetValidError 20105Access Token not yet valid
TVOErrorAccessTokenGrantsInvalidError 20106Invalid Access Token grants
TVOErrorExpirationTimeExceedsMaxTimeAllowedError 20157Expiration Time in the Access Token Exceeds Maximum Time Allowed
TVOErrorAccessForbiddenError 20403Forbidden. The account lacks permission to access the Twilio API
TVOErrorBadRequestError 31400Bad Request. The request could not be understood due to malformed syntax
TVOErrorForbiddenError 31403Forbidden. The server understood the request, but is refusing to fulfill it
TVOErrorNotFoundError 31404Not Found. The server has not found anything matching the request
TVOErrorRequestTimeoutError 31408Request Timeout. A request timeout occurred
TVOErrorConflictError 31409Conflict. The request could not be processed because of a conflict in the current state of the resource. Another request may be in progress
TVOErrorUpgradeRequiredError 31426Upgrade Required. The client should switch to a different protocol
TVOErrorTooManyRequestsError 31429Too Many Requests. Too many requests were sent in a given amount of time
TVOErrorInternalServerError 31500Internal Server Error. The server could not fulfill the request due to some unexpected condition
TVOErrorBadGatewayError 31502Bad Gateway. The server is acting as a gateway or proxy, and received an invalid response from a downstream server while attempting to fulfill the request
TVOErrorServiceUnavailableError 31503Service Unavailable. The server is currently unable to handle the request due to a temporary overloading or maintenance of the server
TVOErrorGatewayTimeoutError 31504Gateway Timeout. The server, while acting as a gateway or proxy, did not receive a timely response from an upstream server
TVOErrorTokenAuthenticationRejected 51007Token authentication is rejected by authentication service
TVOErrorRegistrationError 31301Registration failed. Look at [error localizedFailureReason] for details

Insights

Group NameEvent NameDescriptionSince version
registrationunregistrationUnregistration is successful3.0.0-beta3
registrationunregistration-errorUnregistration failed3.0.0-beta3

An example of using the unregistration API

[TwilioVoice unregisterWithAccessToken:accessToken
    deviceToken:deviceToken
    completion:^(NSError *error) {
        if(error != nil) {
            NSLog("Failed to unregister for incoming push: %@\n\t  - reason: %@", [error localizedDescription], [error localizedFailureReason]);
        } else {
            NSLog("Unregistration successful");
        }
}];

Declared In

TwilioVoice.h

+ handleNotification:delegate:

Processes an incoming VoIP push notification payload.

+ (BOOL)handleNotification:(nonnull NSDictionary *)payload delegate:(nonnull id<TVONotificationDelegate>)delegate

Parameters

payload

Push notification payload.

delegate

A TVONotificationDelegate to receive incoming push notification callbacks.

Return Value

A BOOL value that indicates whether the payload is a valid notification sent by Twilio.

Discussion

This method will synchronously process call notification payload and call the provided delegate on the same dispatch queue.

Twilio sends two types of notifications via Apple VoIP Service, call and cancel. The notification type is encoded in the dictionary with the key twi_message_type and the values twilio.voice.call and twilio.voice.cancel.

A call notification is sent when someone wants to reach the registered identity. Passing a call notification into this method will result in a callInviteReceived: callback with a TVOCallInvite object and return YES.

A cancel notification is sent to an identity for the following reasons:

  • call made to this identity is prematurely disconnected by the caller
  • call is rejected
  • call is ignored
  • after a call is accepted. When a call is accepted, a cancel notification is sent to all the devices that have been registered with the identity accepting the call, even to the device that accepted the call. It is recommended that in this case the developer checks whether the call sid of TVOCancelledCallInvite matches the accepted call, and if so disregard it.

Passing a cancel notification into this method will result in a cancelledCallInviteReceived: callback with a TVOCancelledCallInvite object and return YES.

Insights

Group NameEvent NameDescriptionSince version
connectionincomingIncoming call notification received3.0.0-preview1

An example of using the handleNotification API

@interface CallViewController () <PKPushRegistryDelegate, TVONotificationDelegate, TVOCallDelegate, ... >

// property declarations

@end

@implementation CallViewController

// ViewController setup and other code ...

#pragma mark - PKPushRegistryDelegate

- (void)pushRegistry:(PKPushRegistry *)registry
    didReceiveIncomingPushWithPayload:(PKPushPayload *)payload
    forType:(NSString *)type {
        NSLog(@"Received incoming push: %@", payload.dictionaryPayload);

        if ([type isEqualToString:PKPushTypeVoIP]) {
            if (![TwilioVoice handleNotification:payload.dictionaryPayload delegate:self]) {
                NSLog(@"The push notification was not a Twilio Voice push notification");
        }
    }
}

#pragma mark - TVONotificationDelegate methods

- (void)callInviteReceived:(TVOCallInvite *)callInvite {
    // handle call invite
}

- (void)cancelledCallInviteReceived:(TVOCancelledCallInvite *)cancelledCallInvite {
    // handle cancelled call invite
}

@end

Declared In

TwilioVoice.h

+ connectWithAccessToken:delegate:

Make an outgoing Call.

+ (nonnull TVOCall *)connectWithAccessToken:(nonnull NSString *)accessToken delegate:(nonnull id<TVOCallDelegate>)delegate

Parameters

accessToken

The access token.

delegate

A TVOCallDelegate to receive Call state updates.

Return Value

A TVOCall object.

Discussion

This method is guaranteed to return a TVOCall object. It’s possible for the returned Call to either succeed or fail to connect.

The identity provided in the Access Token may only contain alpha-numeric and underscore characters. Other characters, including spaces, will result in undefined behavior.

The TVOCallDelegate will receive the Call state update callbacks. The callbacks are listed here.

Callback NameDescriptionSince version
call:didFailToConnectWithError The call failed to connect. An NSError object provides details of the root cause.3.0.0-preview1
callDidStartRinging Emitted once before the callDidConnect callback when the callee is being alerted of a Call.3.0.0-preview2
callDidConnect The Call has connected.3.0.0-preview1
call:didDisconnectWithError The Call was disconnected. If the Call ends due to an error the NSError is non-null. If the call ends normally NSError is nil.3.0.0-preview1

If connect fails, call:didFailToConnectWithError or call:didDisconnectWithError callback is raised with an NSError object. [error localizedDescription], [error localizedFailureReason] and [error code] provide details of the failure.

If any authentication error occurs then the SDK will receive one of the following errors.

Authentication ErrorsError CodeDescription
TVOErrorAccessTokenInvalidError20101Twilio was unable to validate your Access Token
TVOErrorAccessTokenHeaderInvalidError20102Invalid Access Token header
TVOErrorAccessTokenIssuerInvalidError20103Invalid Access Token issuer or subject
TVOErrorAccessTokenExpiredError20104Access Token has expired or expiration date is invalid
TVOErrorAccessTokenNotYetValidError20105Access Token not yet valid
TVOErrorAccessTokenGrantsInvalidError20106Invalid Access Token grants
TVOErrorAuthFailureCodeError20151Twilio failed to authenticate the client
TVOErrorExpirationTimeExceedsMaxTimeAllowedError20157Expiration Time in the Access Token Exceeds Maximum Time Allowed
TVOErrorAccessForbiddenError20403Forbidden. The account lacks permission to access the Twilio API
TVOErrorApplicationNotFoundError21218Invalid ApplicationSid

If any connection fails because of any other error then the SDK will receive one of the following errors.

Connection ErrorsError CodeDescription
TVOErrorConnectionError31005Connection error
TVOErrorCallCancelledError31008Call Cancelled
TVOErrorTransportError31009Transport error
TVOErrorMalformedRequestError31100Malformed request
TVOErrorAuthorizationError31201Authorization error
TVOErrorBadRequestError31400Bad Request
TVOErrorForbiddenError31403Forbidden
TVOErrorNotFoundError31404Not Found
TVOErrorRequestTimeoutError31408Request Timeout
TVOErrorTemporarilyUnavailableError31480Temporarily Unavailable
TVOErrorCallDoesNotExistError31481Call/Transaction Does Not Exist
TVOErrorBusyHereError31486Busy Here
TVOErrorRequestTerminatedError31487Request Terminated
TVOErrorInternalServerError31500Internal Server Error
TVOErrorBadGatewayError31502Bad Gateway
TVOErrorServiceUnavailableError31503Service Unavailable
TVOErrorGatewayTimeoutError31504Gateway Timeout
TVOErrorDNSResolutionError31530DNS Resolution Error
TVOErrorDeclineError31603Decline
TVOErrorDoesNotExistAnywhereError31604Does Not Exist Anywhere
TVOErrorSignalingConnectionDisconnectedError53001Signaling connection disconnected
TVOErrorMediaClientLocalDescFailedError53400Client is unable to create or apply a local media description
TVOErrorMediaServerLocalDescFailedError53401Server is unable to create or apply a local media description
TVOErrorMediaClientRemoteDescFailedError53402Client is unable to apply a remote media description
TVOErrorMediaServerRemoteDescFailedError53403Server is unable to apply a remote media description
TVOErrorMediaNoSupportedCodecError53404No supported codec
TVOErrorMediaConnectionError53405Media connection failed

Insights

Group NameEvent NameDescriptionSince version
connectionoutgoingOutgoing call is made3.0.0-beta2

If connection fails then an error event will be published.

Group NameEvent NameDescriptionSince version
connectionerrorerror description3.0.0-beta2

An example of using the connectWithAccessToken:delegate: API

@interface CallViewController () <TVOCallDelegate, ... >

// property declarations

@end

@implementation CallViewController

// ViewController setup and other code ...

- (void)makeCall:(NSString*)accessToken
    self.call = [TwilioVoice connectWithAccessToken:accessToken delegate:self];
}

#pragma mark - TVOCallDelegate

- (void)callDidStartRinging:(TVOCall *)call {
    NSLog(@"Call is ringing at called party %@", call.to);
}

- (void)call:(TVOCall *)call didFailToConnectWithError:(NSError *)error {
    NSLog("Failed to Connect the Call: %@\n\t  - reason: %@", [error localizedDescription], [error localizedFailureReason]);
}

- (void)call:(TVOCall *)call didDisconnectWithError:(NSError *)error {
    if (error) {
        NSLog(@"Call disconnected with error: %@", error);
    } else {
        NSLog(@"Call disconnected");
    }
}

- (void)callDidConnect:(TVOCall *)call {
    NSLog(@"Call connected.");
}

@end

Declared In

TwilioVoice.h

+ connectWithOptions:delegate:

Make an outgoing Call.

+ (nonnull TVOCall *)connectWithOptions:(nonnull TVOConnectOptions *)options delegate:(nonnull id<TVOCallDelegate>)delegate

Parameters

options

The connect options.

delegate

A TVOCallDelegate to receive Call state updates.

Return Value

A TVOCall object.

Discussion

This method is guaranteed to return a TVOCall object. It’s possible for the returned Call to either succeed or fail to connect. Use the TVOConnectOptions builder to specify Call parameters and UUID.

The TVOCallDelegate will receive the Call state update callbacks. The callbacks are same as connectWithAccessToken:delegate: API.

If connect fails, call:didFailToConnectWithError or call:didDisconnectWithError callback is raised with an NSError object. [error localizedDescription], [error localizedFailureReason] and [error code] provide details of the failure. The error codes are same as connectWithAccessToken:delegate: API.

Insights

Group NameEvent NameDescriptionSince version
connectionoutgoingOutgoing call is made3.0.0-beta2

If connection fails then an error event will be published.

Group NameEvent NameDescriptionSince version
connectionerrorerror description3.0.0-beta2

An example of using the connectWithAccessToken:delegate API

@interface CallViewController () <TVOCallDelegate, ... >

// property declarations

@end

@implementation CallViewController

// ViewController setup and other code ...

- (void)makeCall:(NSString *)accessToken uuid:(NSString *)uuid region:(NSString *)region to:(NSString *)phoneNumber
    NSMutableDictionary *params = [NSMutableDictionary dictionary];

    if ([to length] > 0) {
        params[@"Mode"] = @"Voice";
        params[@"PhoneNumber"] = phoneNumber;
    }

    TVOConnectOptions *connectOptions = [TVOConnectOptions optionsWithAccessToken:accessToken
        block:^(TVOConnectOptionsBuilder *builder) {
            builder.params = params;
            builder.uuid = uuid;
            builder.region = region;
    }];

    self.call = [TwilioVoice connectWithOptions:connectOptions delegate:self];
}

#pragma mark - TVOCallDelegate

- (void)callDidStartRinging:(TVOCall *)call {
    NSLog(@"Call is ringing at called party %@", call.to);
}

- (void)call:(TVOCall *)call didFailToConnectWithError:(NSError *)error {
    NSLog("Failed to Connect the Call: %@\n\t  - reason: %@", [error localizedDescription], [error localizedFailureReason]);
}

- (void)call:(TVOCall *)call didDisconnectWithError:(NSError *)error {
    if (error) {
        NSLog(@"Call disconnected with error: %@", error);
    } else {
        NSLog(@"Call disconnected");
    }
}

- (void)callDidConnect:(TVOCall *)call {
    NSLog(@"Call connected.");
}

@end

Declared In

TwilioVoice.h