This guide details how to integrate Mobile Connect into your iOS apps using the Mobile Connect SDK for iOS. It is strongly recommended that you read through this guide and familiarise yourself with the functions the SDK provides before downloading an demo app and starting to code.

The guide describes the processes for:

Prerequisites

Before you can make calls to Mobile Connect, you must have registered for a Mobile Connect user account and registered an application. This will provide you with your developer credentials, which you will need to specify in a configuration object, and your Application Short Name, which is a required parameter when calling the Authorisation or Identity endpoints.

Configuring your Project

Use CocoaPods to add the Mobile Connect framework to your Xcode project.

  1. Install CocoaPods.

  2. Open Terminal and run the following command:

    $ sudo gem install cocoapods
  3. Configure the Podfile and install the framework.

    1. In the Terminal, navigate to your Xcode project directory and run the following command:

      pod install
    2. Open the Podfile in your project directory.
    3. Immediately beneath the target specification line:

      target ‘<target_name>’ do

      add the following:

      Swift 2

      use_frameworks!
      pod 'MobileConnectSDK', :git => 'https://github.com/Mobile-Connect/ios_sdk_v3', :branch => ’release/3.3.5’
      Swift 3

      use_frameworks!
      pod 'MobileConnectSDK', :git => 'https://github.com/Mobile-Connect/ios_sdk_v3', :branch => ’master’

      and then save the Podfile.

    4. Open Terminal, navigate to your Xcode project directory, and run the following command:

      pod update
  4. Add MobileConnectSDK to your project.

    1. Add the framework into your target app’s Linked Frameworks and Libraries.

      1. In the project browser, select the project. The project’s properties are displayed:

        Adding a framework screenshot

      2. On the General tab, in the Targets section, select your target app.
      3. In the Linked Frameworks and Libraries section, click the plus (Add items). A list of frameworks and libraries opens.
      4. Expand the Workspace folder, select MobileConnectSDK.framework, and click Add.

        Select framework screenshot

        The list closes and the framework is added to the Linked Frameworks and Libraries.

        Linked Frameworks and Libraries screenshot

      5. If your project is based on Objective-C, then on the Build Settings tab, set the Allow Non-modular includes in Framework Modules setting to Yes, as shown below.

        Allow Non-modular includes in Framework Modules setting screenshot

    2. If your target builds against iOS 9 or higher, ensure that you have added App Transport Security Settings to your target Info.plist. Open the Info.plist file as source code and add the following key:

      <key>NSAppTransportSecurity</key>
      <dict>
      <key>NSAllowsArbitraryLoads</key><true/>
      </dict>
    3. Import the framework by adding the following into your implementation file:

      • For Objective-C projects, in the .m file, add:

        @import MobileConnectSDK;
      • For Swift projects, in the .swift file, add:

        import MobileConnectSDK;
    4. Before you can access the Mobile Connect library you will need to define the main developer information in your code.

      • Redirect URI
      • Integration endpoint (application endpoint)

        Note: if you operate in the EU then you should use EU Discovery Service domain: eu.discovery.mobileconnect.io

      • Integration key (client key)
      • Integration secret (client secret)

      Add the following code to the appropriate location:

      Objective-C

      [MobileConnectSDK setClientKey:<yourClientKey>];
      [MobileConnectSDK setClientSecret:<yourClientSecret>];
      [MobileConnectSDK setApplicationEndpoint:<yourApplicationEndpoint>];
      [MobileConnectSDK setRedirect:[NSURL URLWithString:<yourRedirectURL>]];

      Swift 2 & Swift 3

      MobileConnectSDK.setClientKey(<yourClientKey>)
      MobileConnectSDK.setClientSecret(<yourClientSecret>)
      MobileConnectSDK.setRedirect(<yourRedirectURL>)
      MobileConnectSDK.setApplicationEndpoint(<yourApplicationEndpoint>)
      MobileConnectSDK.setXRedirect(<yourXRedirectHeaderValue>)

Back to top

Using the SDK with Mobile Connect

The Mobile Connect SDK for iOS automates much of the basic housekeeping and configuration tasks of your application’s integration with Mobile Connect. Many of these functions activate in the Discovery phase, independently of the Identity Gateway endpoint your application will ultimately call, and so are described here for your reference.

Provider Metadata

A successful call to the Mobile Connect Discovery endpoint returns the end user’s Mobile Network Operator (MNO) and describes the Mobile Connect services that MNO supports, via a URI to the MNO’s Provider Metadata. The metadata describes the Identity Gateway endpoints (Mobile Connect services) your application or service can use and how those endpoints are configured – for example, the response types an endpoint can return, the subject identifier types supported, or the Identity Services encryption algorithms in use.

The Mobile Connect SDK handles the querying of the Provider Metadata; if the Provider Metadata URI returns no data, the values from the Discovery response are used. Regardless of the source, the SDK parses the Provider Metadata into a discrete list of properties. See the OpenID Provider Metadata definition for a list of the metadata available, although you should note that Mobile Connect's implementation may not be exhaustive.

The ProviderMetadata object is available as discoveryResponse.metadata, where discoveryResponse is the object returned following a successful call to the Discovery service.

Back to top

Supported Services

Before your application or service can call an Identity Gateway endpoint (scope), you need to know if the MNO supports the scope you are calling. The Mobile Connect SDK provides the method isMobileConnectServiceSupported(String scope) in the discoveryReponse, which can be accessed as follows:

discoveryResponse.isMobileConnectServiceSupported(“mc_authz mc_identity_signup”)

The method accepts a space-separated list of scopes, which it then checks against the list of supported scopes in the Provider Metadata.

  • If all of the scopes passed as arguments are present in the Provider Metadata, the function returns true.
  • If any of the passed scopes are not present in the metadata, the function returns false.
  • If the Provider Metadata is not available, or the scopes attribute is missing, null, or an empty string, the function returns nil.

Back to top

Version Compatibility

Although the MNOs may support differing versions of the Mobile Connect APIs, the SDK automatically detects the version in use at an Identity Gateway from the Provider Metadata, and ensures that the correct Mobile Connect Profile is used when making calls to the Mobile Connect APIs.

Back to top

Application Short Name

The application you register with the Mobile Connect Developer Portal includes an Application Short Name, which is stored in the API Exchange and returned in responses from the Discovery service, and is available as discoveryResponse.applicationShortName. The SDK captures the returned applicationShortName and includes it when constructing calls to the Mobile Connect Authorisation and Identity endpoints. Following a successful call, the Application Short Name is displayed to the end user to identify the application requesting either authorisation for a transaction or permission to share their user information.

Back to top

Mobile Connect Constants

The SDK provides a number of constants for referencing the Mobile Connect services by scope. They are available in the MobileConnectProduct.h header, and can be called directly. For example:

MobileConnectIdentityPhone

calls the scope "openid mc_identity_phonenumber". You can pass multiple scopes as a space-separated string; the SDK will remove any duplicates before making the call to the Identity Gateway.

The following constants are available:

Mobile Connect Product Constant Identifier Literal Value
Authentication (v1.0) MobileConnect "openid"
Authentication (v1.1) MobileConnectAuthentication "openid mc_authn"
Authorisation MobileConnectAuthorization "openid mc_authz"
Identity: Phone Number MobileConnectIdentityPhone "openid mc_identity_phonenumber"
Identity: Signup MobileConnectIdentitySignup "openid mc_identity_signup"
Identity: Signup Plus* MobileConnectR3IdentitySignupPlus "openid mc_identity_signupplus"
Identity: National ID MobileConnectIdentityNationalId "openid mc_identity_nationalid"

*This constant is available to support possible future products.

Back to top

id_token Validation

A successful response from the Identity Gateway includes an id_token – a JSON Web Token, which validates against a JSON Web Keyset (JWKS), available at a URL specified in the Provider Metadata attribute jwks_uri.

The SDK performs a number of automatic validation actions to ensure the integrity of the response source, such as checking whether the token has expired or if its signature is valid. It also fetches the data from the jwks_uri location and stores it alongside the associated Discovery response.

Back to top

Using the MobileConnectManager

The Mobile Connect SDK for iOS offers a number of classes bundled into a single wrapper: MobileConnectManager. The method(s) you call will depend on the combination of Mobile Connect services you want to access and the client information you have available, but in all cases the methods require only the minimum number of parameters from you before returning the required token(s) from the Identity Gateway.

Authentication: Single Button Method

The following procedure describes the simplest method for integrating Mobile Connect Authentication with your application. All you have to do is provide a delegate to receive the main MobileConnectSDK events, and add a button to the storyboards in which it is required. In the background, the MobileConnectManager will do all the work for you, including connecting to the Discovery service, getting operator data, and then connecting to the Mobile Connect Authentication endpoint, after which the delegate receives either a token response or an error.

  1. Ensure that the delegate conforms to the protocol MobileConnectManagerDelegate.

    Objective-C

    @interface ViewController ()<MobileConnectManagerDelegate>
    Swift 2 & Swift 3

    class ViewController : MobileConnectManagerDelegate
  2. Implement the MobileConnectManagerDelegate in that class.

    Objective-C

    - (void)mobileConnectWillStart;
    - (void)mobileConnectWillPresentWebController;
    - (void)mobileConnectWillDismissWebController;
    - (void)mobileConnectDidGetTokenResponse:(TokenResponseModel * _Nonnull)tokenResponse;
    - (void)mobileConnectFailedGettingTokenResponseWithError:(NSError * _Nonnull)error;
    Swift

    func mobileConnectWillStart()
    func mobileConnectWillPresentWebController()
    func mobileConnectWillDismissWebController()
    func mobileConnectDidGetTokenResponse(tokenResponse : TokenResponseModel)
    func mobileConnectFailedGettingTokenResponseWithError(error : NSError)
  3. Provide the delegate to the MobileConnectSDK.

    Objective-C

    [MobileConnectSDK setDelegate:self];
    Swift 2 & Swift 3

    MobileConnectSDK.setDelegate(self)
  4. Drag a view into your storyboard and set its class to MobileConnectManagerButton.

    Dragging a view screenshot

Back to top

Calling Identity Gateway Endpoints: Single Function Method

The following procedure describes how to use the MobileConnectManager class and call an appropriate method depending on whether the client’s phone number is available.

  1. Instantiate the MobileConnectManager.

    Objective-C

    MobileConnectManager *manager = [MobileConnectManager new];
    Swift 2& Swift 3

    let mobileConnectManager : MobileConnectManager = MobileConnectManager()
  2. Call one of the following methods. In each case, provide a controller from which the framework can present its own web controller.

    To obtain an authentication token:

    • If you don’t have the client’s phone number:

      Objective-C

      [manager getTokenInPresenterController:<insertTheControllerFromWhichYouWishtToLaunchMobileConnectHere> withCompletionHandler:^(TokenResponseModel * _Nullable tokenResponseModel, NSError * _Nullable error) {
      
           }];
      Swift 2 & Swift 3

      mobileConnectManager.getTokenInPresenterController(<controllerToPresentTheWebviewController>, clientIP: <yourDeviceIP>) { (userInfoResponse, tokenResponseModel, error) in
      
           }
    • If you have the client’s phone number, provide it as a parameter:

      Objective-C

      [manager getTokenForPhoneNumber:@"<clientPhoneNumberHere>" inPresenterController:self withCompletionHandler:^(TokenResponseModel * _Nullable tokenResponseModel, NSError * _Nullable error) {
      
           }];
      Swift 2 & Swift 3

      mobileConnectManager.getTokenForPhoneNumber("clientPhoneNumberHere", clientIP: <yourDeviceIP>, inPresenterController: <controllerThatWillPresentTheWebViewController>) { 
      (userInfoResponse, tokenResponseModel, error) in
      
           }

    To obtain an authorisation token:

    Objective-C

    [manager getAuthorizationTokenInPresenterController:self withContext:@"context" withStringValueScopes:@[@"scope1"] bindingMessage:@"message" completionHandler:^(TokenResponseModel * _Nullable tokenResponseModel, NSError * _Nullable error) {
            
        }];
    Swift 2 & Swift 3

    mobileConnectManager.getAuthorizationTokenInPresenterController(self, clientIP : <yourDeviceIP>, withContext: "the context", withScopes: [ProductType.Email, ProductType.Profile], bindingMessage: "binding message") { (userInfoResponse, tokenResponseModel, error) in
                print(tokenResponseModel)
         }

    To access the Identity service:

    Objective-C

    [manager getAttributeServiceResponse:self context:@"context" stringScopes:@[@"scope1"] bindingMessage:@"binding message" withCompletionHandler: ^(AttributeResponseModel * _Nullable response, NSError * _Nullable error) {
             
         }];
    Swift 2 & Swift 3

    mobileConnectManager.getAttributeServiceResponse(self, clientIP: <yourDeviceIP>, context: "the context", scopes: [ProductType.IdentityPhoneNumber, ProductType.Phone], bindingMessage: "binding message") { (attributeResponseModel, tokenResponseModel, error) in
         
         }

    Note: methods are available to call the Authorisation and Identity endpoints with the client phone number; see the SDK code for more information.

Back to top

Using the Discovery Service

The MobileConnectManager offers a class – DSService – which allows you to make calls to the Discovery service with more control and flexibility than the end-to-end methods described above. When accessing DSService, you may have the client’s phone number (MSISDN), their network code and country code, or you may have none of their information. To support these use cases, DSService offers three methods based on the information available.

Note: if you operate in the EU then you should use EU Discovery Service domain: eu.discover.mobileconnect.io

The following procedure details making a call to the Discovery service using DSService.

  1. Instantiate the DSService.

    Objective-C

    DSService *discovery = [DSService new];
    Swift 2 & Swift 3

    let discovery : DSService = DSService()
  2. Call one of the following methods:

    • If you don’t have the client’s phone number:

      Objective-C

      [discovery startOperatorDiscoveryInController:<controllerFromWhichToLaunchMobileConnect> completionHandler:^(BaseWebController * _Nullable controller, DiscoveryResponse * _Nullable operatorsData, NSError * _Nullable error) {
      
           }];
      Swift 2 & Swift 3

      discovery.startOperatorDiscoveryInController(<controllerToPresentWebViewController>, clientIP: <yourDeviceIP>) { (controller, operatorsData, error) in
      
           }

      Note: don’t forget to dismiss the controller that you receive in the callback method, otherwise the web view will remain on screen.

    • If you have the client’s phone number:

      Objective-C

      [discovery startOperatorDiscoveryForPhoneNumber:@"<clientPhoneNumber>" completionHandler:^(DiscoveryResponse * _Nullable operatorsData, NSError * _Nullable error) {
      
           }];
      Swift 2 & Swift 3

      discovery.startOperatorDiscoveryForPhoneNumber("<clientPhoneNumber>", clientIP: <yourDeviceIP>) { (operatorsData, error) in
      
           }

      Note: you don’t need to offer a view controller, because there is no need to display a web page to the client.

    • If you have the mobile operator’s country code and network code:

      Objective-C

      [discovery startOperatorDiscoveryWithCountryCode:@"<countryCode>" networkCode:@"<networkCode>" completionHandler:^(DiscoveryResponse * _Nullable operatorsData, NSError * _Nullable error) {
      
           }];
      Swift 2 & Swift 3

      discovery.startOperatorDiscoveryWithCountryCode("<clientOperatorCountryCode>", networkCode: "<clientOperatorNetworkCode>") { (operatorsData, error) in
      
            }

Back to top

Using the Identity Gateway Services

The second class available within the MobileConnectManager – MCService – allows you to build and execute calls against all of the endpoints offered by the Mobile Connect Identity Gateway. It takes as its input the response from the DSService call and a configuration that you specify in your code.

The methods you need to call and the parameters you need to pass depend upon the service you want to use. All variations are detailed in the following procedure.

Note: where no scope is passed, the required service defaults to Authentication, although you can explicitly request Authentication by passing the scope “mc_authn”.

  1. Create a service configuration.

    • Authentication configuration

      Objective-C

      MobileConnectServiceConfiguration *configuration = [[MobileConnectServiceConfiguration alloc] initWithDiscoveryResponse:discoveryResponse assuranceLevel:MCLevelOfAssuranceLevel2 authorizationScopes:@[]];
      Swift 2 & 3

      let authenticationConfiguration : MobileConnectServiceConfiguration = MobileConnectServiceConfiguration(discoveryResponse: response, authorizationScopes: ["<yourScopes>"])
    • Authorisation configuration

      Objective-C

      MCAuthorizationConfiguration *configuration = [[MCAuthorizationConfiguration alloc] initWithDiscoveryResponse:discoveryResponse assuranceLevel:MCLevelOfAssuranceLevel2 authorizationScopes:@[<scope_1>,<scope_2>,…]];
      Swift 2

      let authConfigParam = AuthorizationConfigurationParameters(prompt: "", uiLocale: <yourLocale>, idTokenHint: <yourIDToken>, loginHintToken: <yourLoginHintToken>, responseMode: <yourMode>, claims: <yourClaims>, maxAge: <yourAge>)
      
      let authorizationConfiguration : MCAuthorizationConfiguration = MCAuthorizationConfiguration(discoveryResponse: response, context: "my app context for the user to read", bindingMessage: "binding message", authorizationScopes: [ProductType.Phone], config: authConfigParam, loginHint: <yourLoginHint>)
      Swift 3

      let authConfigParam = AuthorizationConfigurationParameters(prompt: "", uiLocale: <yourLocale>, idTokenHint: <yourIDToken>, loginHintToken: <yourLoginHintToken>, responseMode: <yourMode>, claims: <yourClaims>, maxAge: <yourAge>)
      
      let authorizationConfiguration : MCAuthorizationConfiguration = MCAuthorizationConfiguration(discoveryResponse: response, context: "my app context for the user to read", bindingMessage: "binding message", authorizationScopes: [ProductType.phone], config: authConfigParam, loginHint: <yourLoginHint>)
  2. Use the configuration to instantiate the MCService.

    Objective-C

    MCService *mobileConnectService = [[MCService alloc] initWithConfiguration:configuration];
    Swift 2 & Swift 3

    let service : MCService = MCService(configuration: configuration)
  3. Define a handler to receive the returned token.

    • Authentication token

      Objective-C

      [mobileConnectService getTokenInController:self completionHandler:^(BaseWebController * _Nullable controller, TokenModel * _Nullable tokenModel, NSError * _Nullable error) {
                  
           }];
      Swift 2 & Swift 3

      service.getTokenInController(self, completionHandler: { (controller, tokenModel, error) in
                      
           })
    • Authorization token

      Objective-C

      [mobileConnectService getAuthorizationTokenInController:self completionHandler:^(BaseWebController * _Nullable controller, TokenModel * _Nullable tokenModel, NSError * _Nullable error) {
                  
           }];
      Swift

      service.getAuthorizationTokenInController(self, completionHandler: { (controller, tokenModel, error) in
                      
           })

    Note: don’t forget to dismiss the controller that you receive in the callback method, otherwise the web view will remain on screen.

Back to top

Using Mobile Connect Authorisation

The SDK allows you to call the Identity Gateway with the scope parameter set to “mc_authz”, which signifies an authorisation request for a single transaction (the id_token and access token returned from the Gateway have a timeout set to zero, so expire after a single use). You should check that the Identity Gateway supports version 1.2 of the Mobile Connect Profile (available in the Provider Metadata) before attempting a call, but note that the SDK sets the version to “mc_v1.2” automatically.

The level of authentication required to authorise the transaction defaults to LoA2 (Authorisation), but you can increase it by adding the optional parameter acr_value and setting the value to "3" (for Authorisation Plus).

Back to top

Using Mobile Connect Identity and Attributes

A successful call to the Identity endpoint returns an id_token identifying the user, and an access token that grants your application permission to request their personal information (referred to as Claims). This information contains a range of data; the exact data you can request is specified in the access token, and is limited to those Claims the end user has permitted as part of the original authorisation request.

Note: the access token is for single use only, and expires immediately upon use.

You request access to the Identity endpoint by specifying the appropriate scope in your MCService call. The SDK provides constants that you can pass when requesting specific Identity products:

  • Identity: Phone Number – MobileConnectIdentityPhone
  • Identity: Sign-up – MobileConnectIdentitySignup
  • Identity: National Identity – MobileConnectIdentityNationalId

The SDK also provides convenient enum values in the ProductType enum, which you can use when specifying scopes for Mobile Connect service get token requests.

@objc public enum ProductType : Int
{
    case Authentication
    case Authorization
    case IdentityPhoneNumber
    case IdentitySignUp
    case IdentitySignUpPlus
    case IdentityNationalID
    case Unknown
    case Phone
    case Address
    case Profile
    case Email
}

To make a successful Identity call, you must provide the token response returned by MCService:

ObjectiveC

AttributeService *service = [[AttributeService alloc] initWithTokenResponse:tokenResponse];
    
    [service getAttributeInformation:^(AttributeResponseModel * _Nullable responseModel, NSError * _Nullable error) {
        
    }];
Swift 2 & Swift 3

let attributeService : AttributeService = AttributeService(tokenResponse: tokenResponseModel)
            
attributeService.getAttributeInformation({ (responseModel, error) in
                
})

Further Reference

Back to top