iOS

Skip to end of metadata
Go to start of metadata

Introduction

The iOS client library provides an Objective-C interface for the Gigya API, making it simple to integrate Gigya's service in your iPhone, iPad and iPod Touch applications. This document is a practical step-by-step guide for programmers, explaining how to integrate the Gigya service into their iOS application. Follow the steps below to get started, and use the Library Reference while implementing.

For your assistance, we provide a simple Demo Xcode Project that includes a basic Gigya SDK integration.

  • Gigya's iOS SDK requires iOS 8.0 and above.
  • Gigya's iOS SDK supports iOS 9. See our tips for preparing your app to work with iOS 9.
  • Gigya's iOS SDK supports iOS 10.
  • If you wish to integrate the Gigya service in your server application, please refer to our Server Side SDKs and choose the SDK that suits your development platform.
  • If you want to upgrade an app that was developed with an earlier version, please use the Upgrade Guide to migrate your code.

Download

Download the library archive:

If you are upgrading from a former version, please make sure to read the SDK's Change Log.

Library Guide 

Follow these steps to integrate this library in your iOS application:

  1. Download the Gigya SDK (above)
  2. Gigya Setup - obtain your Gigya API key
  3. Getting Started:
    1. Add GigyaSDK Framework to Your Application's Xcode project
    2. Configure Your Xcode Project
    3. Additional Provider Configuration
  4. Initialization
  5. Logging in the User
  6. Use Gigya's API - Send Requests

You may then refer to:

 

Gigya Setup - Obtain Your Gigya API Key

Go to the Site Dashboard page on Gigya's website. Follow the instructions in the Gigya's Setup guide to setup your application and obtain a Gigya API-Key.

Important: Please make sure to check the Enable Mobile or Desktop Client Applications API Access checkbox in the Permissions page:

 

Getting Started

To get started, you'll need to follow these steps:

a. Add GigyaSDK Framework to Your Application's Xcode Project

  1. Unzip  GigyaSDK.zip and drag the GigyaSDK.framework file into the "Frameworks" folder of your application's Xcode project.
    Note: You need Xcode 4.5 or above to be able to compile with the Gigya SDK framework.
  2. Import the Gigya SDK header:

    #import <GigyaSDK/Gigya.h>
  3. Add the following to your app's AppDelegate:

    - (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options 
    {
        return [Gigya handleOpenURL:url app:app options:options];
    }
     
    - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
    {
        return [Gigya handleOpenURL:url application:application sourceApplication:sourceApplication annotation:annotation];
    }
     
    - (void)applicationDidBecomeActive:(UIApplication *)application
    {
        [Gigya handleDidBecomeActive];
    }

b. Configure Your Xcode Project

  1. Go to your target's settings, then to Build Settings  and set the Other Linker Flags parameter to: -ObjC.
  2. In your app's Info tab, add a URL type and enter your bundle ID as the identifier and scheme:

Note: If your app does not support running in the background, or alternatively you prefer that the Gigya login flow doesn't leave the app, add the "GigyaLoginDontLeaveApp" parameter to your plist and set it to YES.

c. Additional Provider Configuration

Gigya's SDK allows you to use the native login feature from Google and Facebook's SDKs, and Twitter's iOS integrated SSO.

In order to use these providers native logins, additional configurations are needed. Please refer to the relevant sections:

Initialization

The Gigya class is the central class of the Gigya iOS SDK. The class methods of the Gigya class provide access to the Gigya login, connections, and global settings.

As a first step for using Gigya service, insert the following code in your app's AppDelegate  didFinishLaunchingWithOptions method:

[Gigya initWithAPIKey:@"PUT-YOUR-APIKEY-HERE" application:application launchOptions:launchOptions];

You should only call initWithAPIKey once.

 

Note: If your site has been set up to use any non-US data center, you have to specify during initialization that API requests should be sent to the "<DC>.gigya.com" domain (where DC is your data center). Your initWithAPIKey call should therefore look similar to this:

[Gigya initWithAPIKey:@"PUT-YOUR-APIKEY-HERE" application:application launchOptions:launchOptions APIDomain:@"eu1.gigya.com"];
See the initWithAPIKey:APIDomain: method reference for more information.

Logging in the User

The first interaction with Gigya must always be logging in. If the user is not logged in, you cannot access his social profile nor perform social activities, such as setting his status. The quickest way to implement login is using one of the showLoginProvidersDialog methods of the Gigya class. The methods open a login user interface, which presents a selection of providers' icons, enabling the user to login via their social network / webmail account.

If your site is using Gigya's RaaS, see Using Gigya Plugins in the iOS SDK.

 

Note: In Apple's iOS 8 there is a known issue: window.close does not work. This means that Gigya's login success window does not close in iOS 8, so the user will need to close it themselves.

 

 

Here is a screenshot of the login dialog:

In order to implement Login with Facebook you need to add Facebook native login to your app. For more information go to Facebook native login section.

 

The following code displays the providers selection login dialog (with specified login providers ):

[Gigya showLoginProvidersDialogOver:self
    providers:@[@"facebook", @"twitter", @"googleplus"]
    parameters:nil
    completionHandler:^(GSUser *user, NSError *error) {        
        if (!error) {
            // Login was successful
        } else if (error.code == GSErrorAccountPendingRegistration) {
            // Handle user account pending registration. User info already exists in user object.
        } else {
            // Handle error
    }
}];

You may also display a specific provider login directly without showing the providers selection dialog, by calling loginToProvider with the specified provider: 

[Gigya loginToProvider:@"facebook"
    parameters:nil
	over:self
    completionHandler:^(GSUser *user, NSError *error) {       
        if (!error) {
            // Login was successful
        } else if (error.code == GSErrorAccountPendingRegistration) {
            // Handle user account pending registration. User info already exists in user object.
        } else {
            // Handle error
   		}
}];

 

Social Registration

Please refer to our Social Login guide, which provides a specification of Gigya's complete best-practice login/registration flows. Please note that the guide provides step-by-step implementation instructions using our Web SDK. To implement you'll need to substitute the JavaScript methods with parallel iOS SDK methods (the highlight methods are the ones described above).

 

Site Credentials

If you wish to implement site login (using your own login form, and site credentials) alongside with Gigya login, read below how to synchronize site login with Gigya Service.

 

Registering for Gigya Global Events

The Gigya SDK provides two global delegates that are notified with session changes, based on whether you are using Gigya's Social Login  package ( GSSocializeDelegate ) or Registration-as-a-Service  package ( GSAccountsDelegate ).

For example, using GSSocializeDelegate:

 

@interface GTExampleViewController () <GSSocializeDelegate>
@end
@implementation GTExampleViewController
- (void)viewDidLoad
{
    [super viewDidLoad];
    [Gigya setSocializeDelegate:self];
}
- (void)userDidLogin:(GSUser *)user
{
    // User was logged in
}
- (void)userDidLogout
{
    // User was logged out
}
- (void)userInfoDidChange:(GSUser *)user
{
    // User info has changed (connection added, connection removed, etc)
}
@end

 

Sending a Request

After you have logged in the user, you may use the GSRequest class to access the user profile and perform various activities. The following code sends a request to set the current user's status to "I feel great":

// Step 1 - Create the request and set the parameters
GSRequest *request = [GSRequest requestForMethod:@"socialize.setStatus"];
[request.parameters setObject:@"I feel great" forKey:@"status"];

// Step 2 - Send the request and handle the response
[request sendWithResponseHandler:^(GSResponse *response, NSError *error) {
    if (!error) {
        // Request was successful
    else {
        // Handle error
    }
}];

 

The response handler receives GSResponse and NSError parameters. If the operation was successful, error will be nil. Otherwise, you can check the error object (see GSErrorCode enum for error codes) or response to learn why it failed.

For example - handling a 'getUserInfo' response:
The response of 'getUserInfo' includes user information in its data field.

GSRequest *request = [GSRequest requestForMethod:@"socialize.getUserInfo"];
[request sendWithResponseHandler:^(GSResponse *response, NSError *error) {
    if (!error) {
        NSString *nickname = response[@"nickname"];
        NSString *age = response[@"age"];
        NSLog(@"User name: %@ User age: %@", nickname, age);
    }
    else {
        NSLog(@"Got error on getUserInfo: %@", error);
    }
}];

Example - Publishing User Action

The following code sample sends a request to publish a user action to the newsfeed stream on all the connected providers which support this feature.

The socialize.publishUserAction method has a complex parameter called userAction, which defines the user action data to be published. To define the userAction parameter you can either use NSDictionary objects or provide a JSON string, as shown in the two examples below:

Option A - Using NSDictionary objects

// Create the media item to add to the user action
NSDictionary *mediaItem = @{ @"src": @"http://www.infozoom.ru/wp-content/uploads/2009/08/d06_19748631.jpg",
                             @"href": @"http://www.gigya.com",
                             @"type": @"image" };

// Create the user actionNSDictionary *userAction = @{ @"title": @"This is my title",
                              @"userMessage": @"This is my user message",
                              @"description": @"This is my description",
                              @"linkBack": @"http://gigya.com",
                              @"mediaItems": @[ mediaItem ] };

// Create the request and add the userAction parameter
GSRequest *request = [GSRequest requestForMethod:@"socialize.publishUserAction"];
[request.parameters setObject:userAction forKey:@"userAction"];

// Send the request
[request sendWithResponseHandler:^(GSResponse *response, NSError *error) {
    // Handle the response
}];

Option B - Using a JSON String

// Create the action item JSON string
NSString *actionJSON = @"{\"title\":\"This is my title\", \"userMessage\":\"This is a user message\", \"description\":\"This is a description\",\"linkBack\":\"http://www.gigya.com/\", \"mediaItems\":[ {\"src\":\"http://www.f2h.co.il/logo.jpg\", \"href\":\"http://www.gigya.com/\",\"type\":\"image\"}]}";

// Create the request and add the userAction parameter
GSRequest *request = [GSRequest requestForMethod:@"socialize.publishUserAction"];
[request.parameters setObject:actionJSON forKey:@"userAction"];

// Send the request
[request sendWithResponseHandler:^(GSResponse *response, NSError *error) {
    // Handle the response
}];

 

To learn more about publishing user actions, please read the Advanced Sharing guide.

Configuring Native Login

Adding Facebook Native Login

Adding Facebook native login to your iOS app is mandatory if you want to log in via Facebook.

Your Facebook application must be configured for native mobile login. To do this, configure your Facebook app according to the steps described in Facebook's documentation.

Follow these steps to utilize Facebook's native login for iOS:

  1. Add the Facebook iOS SDK  to your project (please consult the release notes to see the latest supported version).
  2. Add the following two parameters to your app's .plist file:
    • FacebookAppID - your Facebook's application ID.
    • FacebookDisplayName - your Facebook's application Display Name as you configured in the App Dashboard.
  3. Create an array key called URL types with a single array sub-item called URL Schemes . Give this a single item with your app ID prefixed with fb. This is used to ensure the application will receive the callback URL of the web-based OAuth flow. For example, if your application's id is 1234, the value should be "fb1234".
  4. When calling showLoginProvidersDialog, make sure to pass "facebook" in the  providers  parameter:

    [Gigya showLoginProvidersDialogOver:self
                     providers:@[@"facebook", @"twitter", @"googleplus"]
                     parameters:nil
                     completionHandler:^(GSUser *user, NSError *error) {
                          if (!error) {
                              // Login was successful
                          } else {
                              // Handle error
                          }
                      }];
    


    You may also display the Facebook login directly without showing the providers selection dialog, by calling loginToProvider with "facebook" as the provider:

    [Gigya loginToProvider:@"facebook"
        	parameters:nil
    		over:self
    	    completionHandler:^(GSUser *user, NSError *error) {
        	    if (!error) {
            	    // Login was successful
            	} else {
                	// Handle error
             }
         }];
    
  5. If you have multiple Facebook apps using the same Facebook app ID, as described in Facebook's documentation, you should concat the URL scheme suffix to the app ID in the .plist file, and add another parameter:
    • FacebookUrlSchemeSuffix - your application's URL scheme suffix.
  6. On success of Facebook login, Gigya will initialize the Facebook SDK's active session, which is accessible at FBSession.activeSession. You can now use Facebook's SDK functionality with this created session. The Facebook login token will be cached, and the session will be automatically opened the next time the app is opened. In order to clear the session, use the Gigya logout method.
  7. If you want to ask the user for additional permissions, you need to use the Gigya class requestNewFacebookPublishPermissions or requestNewFacebookReadPermissions.

 

Adding Google Native Login

Adding Google native login to your iOS app is mandatory if you want to offer log in via Google. Utilizing this functionality on your app, your users will be able to authenticate natively through Google.

To do this configure a Google APIs Console project, according to the steps described in the documentation for Google.

If you are currently using the older Google+ native login in Gigya's iOS SDK v3.4.9 and earlier, you must upgrade to v3.5.0 or later before January 1, 2017, when Google will sunset their Google+ native login which has been replaced by Google Sign-In.

Start integrating Google Sign-In for iOS in your app:

  1. Using CocoaPods: https://developers.google.com/identity/sign-in/ios/start-integrating.

    Without using CocoaPods: https://developers.google.com/identity/sign-in/ios/sdk/.
     
  2. Add the following parameter to your app's .plist file:
    • GoogleClientID  - your iOS client ID.
       
  3. When calling showLoginProvidersDialog, make sure to pass "googleplus" in the providers parameter:

    [Gigya showLoginProvidersDialogOver:self
                 providers:@[@"facebook", @"twitter", @"googleplus"]
                 parameters:nil
                 completionHandler:^(GSUser *user, NSError *error) {
                  if (!error) {
                      // Login was successful
                  } else {
                      // Handle error
                  }
              }];
    


    You may also display the Google login directly without showing the providers selection dialog, by calling loginToProvider with '"googleplus" as the provider:

    [Gigya loginToProvider:@"googleplus"
            parameters:nil
    		over:self
         	completionHandler:^(GSUser *user, NSError *error) {
             if (!error) {
                 // Login was successful
             } else {
                 // Handle error
             }
    
    	}];

    Note: If you want certain scopes, you must specify them in the googlePlusExtraPermissions  parameter, passing a comma-delimited list of Google scopes URLs.

  4. The Google login token will be cached, and the session will be automatically opened the next time the app is opened. In order to clear the session, use the Gigya logout method.

Adding Twitter Single Sign-on

If Twitter Single Sign-on (SSO) is enabled and a Twitter account is defined on an iOS device, the user does not need to provide username and password when logging in with Twitter. 

Simply add  Social.framework and  Accounts.framework  to  your project:

 

Notes:

  • If there is more than one Twitter account available on the device, Gigya will display an account chooser to select an account to SSO with.
    • This requires passing a UIViewController object to the login method.
  • If there is no logged-in Twitter user, or the Single Sign-on failed for some reason (other than the user cancelling the login), Gigya will fallback to the regular webview login.
  • To disable Twitter login, in your app's  .plist file: add and set the DisableTwitterNativeLogin  Boolean parameter to YES.

 

Using Touch ID

Gigya's iOS SDK supports Touch ID from version 3.5.2 and above. Touch ID is supported on iOS 8 and later, the iPhone 5s or later, iPad Pro, iPad Air 2, or iPad mini 3 or later.

Touch ID enables a much higher level of security for your app by verifying that the user is, in fact, the device owner. When this feature is enabled in the SDK, sessions are encrypted using the following methods:

  1. If Touch ID is supported by the device and a fingerprint has been registered - Touch ID is used.
  2. If Touch ID is supported by the device but fingerprints haven't been registered - the device passcode is used.
  3. If the device doesn't have a passcode or the device uses iOS 7, standard keychain encryption is used.

To enable Touch ID, add the following parameters to your .plist:

  • GigyaTouchIDEnabled   = YES (default = NO)
  • GigyaTouchIDMessage = "<custom Touch ID message>" (default = "Please authenticate to proceed”).

When Touch ID is enabled, native login will continue to work as expected (if your app uses native login), but provider sessions will not be automatically refreshed.

User Experience

When Touch ID is enabled, the user will be prompted to authenticate during the last step when logging in to your app. Once authenticated, the session is encrypted and the user may use your app.

After that time, Touch ID authentication takes place:

  • When the app is re-opened, before the first call to a Gigya API. In this context, re-opened means that the app was closed. Switching apps does not cause an app to close.
  • When a session has expired, before the first call to a Gigya API.

Generally, users will not be asked to authenticate more than once per running of your app. 

 

Integrating Your Site with the iOS SDK

GSWebBridge connects the Gigya Web SDK to the Gigya iOS SDK. Any UIWebView can be registered to use the web bridge. Doing this gives the following benefits:

  • Session state will be synchronized. If the user is logged in and the session is active in the iOS SDK, he will be automatically logged in via the JS SDK.
  • Any API requests by the JS SDK will be routed through the iOS SDK, using the iOS SDK session.

  • Any social login process (showLoginProvidersDialog) invoked by the JS SDK will be handled by the iOS SDK, creating a seamless login experience, using Safari or the provider’s native login.
    • GSWebBridge does not support RaaS Screen-Sets. When implementing Gigya RaaS be sure to use the GSPluginView class to load your Screen-Sets.

 

To register a web view, follow these steps:

  1. Call registerWebView:delegate: before the web view has started loading:

    [GSWebBridge registerWebView:webView delegate:self];
  2. Add the following code to your UIWebViewDelegate implementation:

    1. In the beginning of webView:shouldStartLoadWithRequest:navigationType::

      if ([GSWebBridge handleRequest:request webView:webView]) {
        return NO;
      }
      
    2. In webViewDidStartLoad::

      [GSWebBridge webViewDidStartLoad:webView];
  3. Unregister the web view when finished:

    [GSWebBridge unregisterWebView:webView];
  4. To make sure cookie policy does not block the Gigya JS SDK:

    [NSHTTPCookieStorage sharedHTTPCookieStorage].cookieAcceptPolicy = NSHTTPCookieAcceptPolicyAlways;"

 

Implementing WKWebView

The Gigya iOS SDK fully supports using WKWebView in place of UIWebView, however, it's usage differs slightly. If you attempt to exchange usage of WKWebView directly with UIWebView, the SDK will return an exception, since the two use different selectors.

The exception is thrown due to the [GSWebBridge webViewDidStartLoad:webview] selector only accepts UIWebView.

To overcome this and implement the WKWebView with the GSWebBridge, please consult the following example code, which uses Objective-C with the Gigya iOS SDK.

@implementation SomeViewController
 
-(void)viewDidLoad
{
    [super viewDidLoad];
    
    self.wkWebView = [[WKWebView alloc] init];
    [GSWebBridge registerWebView:self.wkWebView delegate:self];
    [self.wkWebView setNavigationDelegate:self];
    [self.wkWebView loadRequest:@"http://urlOfThePageToDisplay"];
}
 
-(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    if ([GSWebBridge handleRequest:[navigationAction request] webView:webView]) {
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
 
    decisionHandler(WKNavigationActionPolicyAllow);
}
 
@end

Using Gigya Plugins in the iOS SDK

GSPluginView is a custom UIView that renders Gigya JS Plugins and integrates them seamlessly with the Gigya iOS SDK.

GSPluginView  currently supports the following plugins:

  • Comments - comments.commentsUI. Note: commenting is supported, but sharing the comment to social networks is not supported. 
  • Reviews - comments.commentsUI.
  • RaaS Screen-Sets - accounts.screenSet.
  • Share Bar - socialize.ShareBarUI. Please note: the share buttons that implement providers' own (native) buttons are not supported. These include Facebook's native Facebook Like  button, Twitter's  Tweet  button, and more. For the full list please refer to the shareButtons parameter in socialize.showShareBarUI.

You can either use Gigya's showPluginDialogOver:plugin:parameters: to display the GSPluginView modally, or  alternatively, for more control and customization, you can create an instance yourself and add it to your view.

Important Note

When calling specific APIs using a mobile SDK, the plugin name is not always inputted the same as it is for Web or REST. 

Whenever you are using an API that begins with 'show', i.e., showScreenSet, showCommentsUI, etc.

  • Do not include the 'show' segment of the API name and convert the new first letter of the API to lower-case:
    • showScreenSet will be screenSet
    • showCommentsUI will be commentsUI

      #For example, with accounts.showScreenSet in the Cordova SDK you would use the following:
      gigyaClient.showPlugin('accounts.screenSet', { 'screenSet': 'Default-RegistrationLogin' },

*A notable exception to this is socialize.showLoginUI which is still showLoginUI in both Android and iOS SDKs and not currently supported in the Cordova SDK.

An example for using showPluginDialogOver to display GDPluginView modally:

 

NSMutableDictionary *params = [NSMutableDictionary dictionary];
[params setObject:@"comments1" forKey:@"categoryID"];
[params setObject:@"1" forKey:@"streamID"];
[Gigya showPluginDialogOver:self plugin:@"comments.commentsUI" parameters:params completionHandler:nil delegate:self];

 

An example for creating an instance yourself:

 

GSPluginView *pluginView = [[GSPluginView alloc] initWithFrame:CGRectMake(0, 0, 320, 200)];pluginView.delegate = self;
[pluginView loadPlugin:@"comments.commentsUI" parameters:params];
[self.view addSubview:pluginView];

Sessions

The SDK handles all session information internally and enables Gigya to maintain the Login State according to your site Policy settings or Global Conf object.

Once a user is logged in via the SDK, they will be considered logged in to all available plugins that are then loaded.

Advanced Topics

Site Login - Synchronizing with Gigya Service

When a user authenticates using your existing login form or when a new user registers using site registration, it is important to notify Gigya of the user's new state, so as to provide consistent user experience and have access to Gigya's API. The following chart diagram illustrates the implementation:

 

  • Steps 1-3: Your standard site login/registration flow.
  • Step 4: Call the socialize.notifyLogin API method. Pass the following parameters:
    • siteUID  - set this parameter with the user ID that you have designated for this user in your database. The notifyLogin call registers a new user in Gigya in case the siteUID provided is new, or reconnects a returning user in case the siteUID already exists in our records.
    • targetEnv  - set this parameter to "mobile". This determines the server response data fields.
    • newUser  - If it is a new user set the  newUser  parameter to 'true'. This will enable Gigya to distinguish between a new site user and a returning site user, allowing Gigya to analyze users' login/registration behavior with or without Social Login and compare the ratio.
  • Step 5: The notifyLogin response data includes the following fields: sessionToken and sessionSecret
    The following code is the implementation of steps 4,5 using Gigya's Java SDK:

    // Define the API-Key and Secret key (the keys can be obtained from your site setup page on Gigya's website).
    final String apiKey = "PUT-YOUR-APIKEY-HERE";
    final String secretKey = "PUT-YOUR-SECRET-KEY-HERE";
    
    // Defining socialize.notifyLogin request 
    String methodName = "socialize.notifyLogin";
    GSRequest request = new GSRequest(apiKey, secretKey, method);
    request.put("siteUID", "12345");  // The ID you have designated to this user
    request.put("targetEnv", "mobile");
    request.put("newUser", true);  // whether or not this user is new (registration vs login)
    
    GSResponse response = request.send();
    
    if (response.getErrorCode() == 0)
    { 
        String sessionToken = response.getString("sessionToken");
        String sessionSecret = response.getString("sessionSecret");
        /* send the sessionToken & sessionSecret to the client app
        ...
    
        */
    }
    else {
        System.out.println("Got error on notifyLogin: " + response.getLog());
    }
    
  • Step 6: Pass the sessionToken and sessionSecret to your client app.
  • Step 7: Create a session on your client app using the  sessionToken and sessionSecret fields, so as to maintain the client application synchronized with the user state. Use the Gigya setSession method:

    NSString *sessionToken; // initialize with the sessionToken received in response of notifyLogin
    NSString *sessionSecret; // initialize with the sessionSecret received in response of notifyLogin
    NSDate *expirationTime = [NSDate dateWithTimeIntervalSinceNow:36000];
    GSSession *session = [[[GSSession alloc] initWithSessionToken:sessionToken secret:sessionSecret expiration:expirationTime] autorelease];
    [Gigya setSession:session];
  • Step 8: As long as the session is valid (not expired and has valid token), the client app will have access to Gigya's API.

Checking the Session Status 

As user sessions can expire for various reasons (like a timeout) and Gigya's API is only available through a valid session, it is recommended to perform validity checks before calling API methods on an uncertain session status.

The following code validates the current session by calling isSessionValid for the current user session:

 

if ([Gigya isSessionValid]) {
    // Logged in
}

 

Verifying Signatures from Mobile Logins

The process for verifying UID signatures generated from logins via our mobile SDKs depends on whether your API key begins with 2_xxx (older) or 3_xxx (newer).

For API keys beginning with 2_xxx the process is as follows:

  1. Upon user login, grab the "token" and "secret" from the active GSSession.
  2. Over HTTPS, pass this accessToken and secret to your application server.
  3. Call getUserInfo (without specifying a UID) passing the accessToken and secret as the API Key and Secret Key (respectively) to the Gigya API.
  4. Assuming the accessToken and secret that you received in iOS is valid, you will receive a valid response from the getUserInfo call.


For API keys beginning with 3_xxx the process is as follows:

  1. Upon user login, grab the UID, Signature, and Timestamp from the response and pass it to your application server.
  2. Use your server-side SDK's SigUtils.validateUserSignature() method, passing in the data you received from step 1 and your Gigya secret key.
     

Handling Callbacks Manually

App developers who implement the ' application:openURL:sourceApplication:annotation: ' selector (wish to handle incoming events manually), should first check if the event is a Gigya event which should be handled by the Gigya SDK to avoid unexpected errors.

The following code should be placed in AppDelegate.m to enable the Gigya SDK to handle incoming Gigya events:

 

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options 
{
    return [Gigya handleOpenURL:url app:app options:options];
}
 
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    BOOL wasHandled = [Gigya handleOpenURL:url
                             application:application
                             sourceApplication:sourceApplication
                             annotation:annotation];
    if (wasHandled)
        return NO;

    // Enter your handler code here
}

 

Handling Screen-Set Events

The following is an example of code to handle screen-set events, i.e., onAfterScreenLoad of the Registration screen-set.

@interface MyViewController : UIViewController <GSPluginViewDelegate> 

@end 

@implementation MyViewController 

- (void)viewDidLoad
{
    [super viewDidLoad];


    [Gigya showPluginDialogOver:self 
           plugin:@"accounts.screenSet" 
           parameters:params 
           completionHandler:nil 
           delegate:self]; 
} 

- (void)pluginView:(GSPluginView *)pluginView firedEvent:(NSDictionary *)event 
{ 
    NSLog(@"Plugin event from %@ - %@", pluginView.plugin, [event objectForKey:@"eventName"]); 
}


- (void)pluginView:(GSPluginView *)pluginView finishedLoadingPluginWithEvent:(NSDictionary *)event
{
    NSLog(@"Finished loading plugin: %@", pluginView.plugin);
} 


- (void)pluginView:(GSPluginView *)pluginView didFailWithError:(NSError *)error
{
    NSLog(@"Plugin error: %@", [error localizedDescription]);
}

@end

 

Demo Xcode Project

We have created for your assistance a simple Xcode project that integrates Gigya's iOS SDK, with basic usage.

Download the GigyaDemo Project.

The demo project is preconfigured with site API key and native login for Facebook, Google and Twitter.

About the Demo

The demo project is a simple application, which implements Gigya's login and retrieves the user's friends list. The user can also add connections and log out.

The project is configured in the same manner as described in the  Getting Started  section above.

Before deploying any new project to production, it is recommended best practice to always test on a live device first.