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.

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

  insights

Specify reporting statistics to Insights.

@property (nonatomic, assign, class, getter=isInsightsEnabled) BOOL insights

Discussion

Sending stats data to Insights is enabled by default.

Declared In

TwilioVoice.h

  region

Defines the region (Twilio data center) used for media and signaling traffic.

@property (nonatomic, copy, class, nonnull) NSString *region

Discussion

The default region uses Global Low Latency routing, which establishes a connection with the closest region to the user. If you are specifying a region via the TwilioVoice.region property you must do so before [TwilioVoice connectWithAccessToken:delegate:] or [TwilioVoice handleNotification:delegate:delegateQueue:] is called.

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. This error is raised when an HTTP 426 response is received. The reason for this is most likely because of an incompatible TLS version. To mitigate this, you may need to upgrade the OS or download a more recent version of the SDK.
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. This error is raised when an HTTP 426 response is received. The reason for this is most likely because of an incompatible TLS version. To mitigate this, you may need to upgrade the OS or download a more recent version of the SDK
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:delegateQueue:

Processes an incoming VoIP push notification payload.

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

Parameters

payload

Push notification payload.

delegate

A TVONotificationDelegate to receive incoming push notification callbacks.

delegateQueue

The queue where the [TVONotificationDelegate cancelledCallInviteReceived:error:] method will invoked. By default the main dispatch queue will be used.

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.

If you are specifying a region via the TwilioVoice.region property you must do so before calling this method.

Twilio sends a call notification via Apple VoIP Service. The notification type is encoded in the dictionary with the key twi_message_type and the value twilio.voice.call.

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.

To ensure that a cancellation is reported via the [TVONotificationDelegate cancelledCallInviteReceived:error:] callback, the TVOCallInvite must be retained until the call is accepted or rejected.

Insights

Group NameEvent NameDescriptionSince version
connectionincomingIncoming call notification received3.0.0-preview1
connectionlistenReported when an attempt to listen for cancellations is made5.0.0
connectionlisteningReported when an attempt to listen for cancellations has succeeded5.0.0
connectioncancelReported when a cancellation has been reported5.0.0
connectionlistening-errorReported when an attempt to listen for a cancellation has failed5.0.0
registrationunsupported-cancel-message-errorReported when a “cancel” push notification is processed by the SDK. This version of the SDK does not support “cancel” push notifications5.0.0

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

Connecting Calls

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

If you are specifying a region via the TwilioVoice.region property you must do so before calling this method.

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
TVOErrorAddressIncompleteError31484The phone number is malformed
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.

If you are specifying a region via the TwilioVoice.region property you must do so before calling this method.

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;
    }];

    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