Was this article helpful?

iOS

Modified 12:14, 6 May 2013 by Tanya

The iOS client library provides an Objective-C interface for the Gigya API. The library makes 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 who wish 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.

Note: Gigya's iOS SDK requires iOS 4.3 and above.

Note: 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.

 

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 

Please follow these steps to integrate this library in your iOS application:

  1. Download the library archive (above).
  2. Gigya Setup - obtain your Gigya API key
  3. Getting Started
    1. Add Gigya iOS Client Library to your Xcode project
    2. Configure Your Xcode Project
  4. Initialize - create an instance of class GSAPI
  5. Login the User
  6. Use Gigya's API - Send Requests

You may then refer to Advanced Topics for advanced integration issues.

 

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:

mobile_permissions.gif

 

Getting Started

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

a. Add Gigya iOS Client Library to your Application's Xcode Project

  1. Unzip  GSSDK.embeddedframework.zip and drag the "GigyaSDK.embeddedframework" folder 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 GSAPI header:
#import <GigyaSDK/GSAPI.h>

 

b. Configure Your Xcode Project

In order to support Facebook SSO and Twitter SSO, the following frameworks should be added to your project:

  • Social.framework (optional for iOS<6)
  • AdSupport.framework (optional for iOS<6)
  • Accounts.framework (optional for iOS<5)
  • Twitter.framework (optional for iOS<5)

Please go to Project Properties >> Build Phases section, under the "Link Binary With Libraries" section, add the frameworks listed above:

iOS-SDK-Libraries.png

Note: You may use the 'Optional' flag for iOS6-specific frameworks if you would like your app to also build for older versions of the operating systems.

 

Next you need to add the -lsqlite3.0 SQL library and the -ObjC linker flag to the list of build dependencies in the Build Settings pane:

iossqlite1.png

iossqlite2.png

iossqliteobjc.png

 

 

Initialization - Create an Instance of GSAPI Class

Class GSAPI is the central class of the Gigya iOS SDK. The instance of the GSAPI class provides access to the Gigya service.
As a first step for using Gigya service, create an instance of GSAPI, assuming there is a variable called gsAPI:

gsAPI = [[GSAPI alloc] initWithAPIKey:@"PUT-YOUR-APIKEY-HERE"];

Note: You should only call initWithAPIKey once.

Class GSAPI's initialization method receives one parameter:

  • APIKey - your Gigya API key, which you have obtained in the previous step.

You should create only one GSAPI object, and retain it for the lifetime of your application.
 

Logging in the User

The first interaction with Gigya must always be logging in. If the user is not logged in, you cannot access her social profile nor perform social activities, such as setting her status. The quickest way to implement logging-in is using the showLoginUI method of class GSAPI. The method opens a login user interface, which presents a selection of providers' icons, enabling the user to login via his social network / webmail account. Here is a screenshot of the login UI:

iPhone-LoginUI.png

 

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

// Present the Login user interface.
GSObject* pParams = [[GSObject alloc] init];
[pParams putStringValue:@"facebook,twitter,google" forKey:@"enabledProviders"];
[gsAPI showLoginUI:pParams ViewController:self delegate:nil context:nil];
[pParams release];

Note: If you wish to implement the graphic design by yourself use the login method instead.

 

Registering to the gsLoginUIDidLogin Event

After the user has successfully logged in, Gigya fires an 'gsLoginUIDidLogin' event. You may register to the event, receive a notification from Gigya when the login process concludes, and apply post login operations (such as updating the UI). To implement that, you will need to:

  1. Define a class that conforms to the GSLoginUIDelegate protocol (this may be your main UIViewController class):

    @interface YourClass UIViewController<GSLoginUIDelegate> {
    ...

     
  2. Implement the gsLoginUIDidLogin method. In your implementation include actions that should follow a successful login:

    // Fired when the login operation completes
    - (void)  gsLoginUIDidLogin:(NSString*)provider user:(GSObject*)user context:(id)context;
    {
         NSLog(@"gsLoginUIDidLogin: provider=%@ user=%@ context=%@",provider,[user stringValue],context);
    }

     
  3. When executing the showLoginUI method, pass an instance of your delegate object as the second parameter:
    // Present the Login user interface.
    // Register to the login event (2nd parameter).
    // in this example 'self' conforms to the GSLoginUIDelegate protocol 
    [gsAPI showLoginUI:nil delegate:self context:nil];

 

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

 

Sending a Request

After you have logged in the user, you may use the GSAPI to access the user profile and perform various activities. This is implemented using the GSAPI's sendRequest method. The following code sends a request to set the current user's status to "I feel great":

// Step 1 - Defining request parameters
GSObject *pParams = [[GSObject alloc] init];
[pParams putStringValue:@"I feel great" forKey:@"status"];     // set the "status" parameter to "I feel great"

// Step 2 - Sending the request
[gsAPI sendRequest:@"socialize.setStatus" params:pParams delegate:nil context:nil]
[pParams release];

 

Step 1: Define the Request Parameters

Create a GSObject instance and fill it with parameters. There are two ways to define the parameters:

1. Construct a GSObject from JSON string. For example:

GSObject *pParams = [GSObject objectWithJSONString:@"{param1:'value1', param2:'value2', param3:'value3',...}"];

2. Construct an empty GSObject and add parameters using the put method:

GSObject *pParams =[[GSObject alloc] init];
[pParams putStringValue:@"value1" forKey:@"param1"];
[pParams putStringValue:@"value2" forKey:@"param2"];
[pParams putIntValue:1000 forKey:@"param3"];
...
[pParams release];

When a parameter is a complex object, you can use compound GSObjects or a JSON string as the value. Please refer to the example below.

 

Note: in the REST API reference you may find the list of available Gigya API methods and the list of parameters per each method. 

 

Step 2: Sending the Request

Execute the sendRequest method:

[gsAPI sendRequest:@"socialize.setStatus" params:pParams delegate:nil context:nil]

The parameters of the method are:

  1. method - the Gigya API method name. Please refer to the REST API reference for the list of available methods.
  2. params - the parameters' object that you have created in Step 1.
  3. delegate - you may register a response delegate object. The following section will guide you through this.
  4. context - an optional object that is passed back with the response.

 

Handling a Response

Gigya replies with a response to each request that you send. To define a response delegate, define an interface which implements the GSResponseDelegate protocol. The gsDidReceiveResponse method implementation should handle the response.

Step 1 - define a class that conforms to the GSResponseDelegate protocol (this may be your main UIViewController class):
@interface YourClass UIViewController<GSResponseDelegate> {
...

Step 2 - implement the gsDidReceiveResponse method:
- (void) gsDidReceiveResponse:(NSString*)method response:(GSResponse*)response context:(id)context
{
         
	 NSString *resMsg = [NSString stringWithFormat:@"\n errorCode=%d\n errorMessage=%@\n response.data=%@\n", 
					   response.errorCode, response.errorMessage, [response.data stringValue]];
	 NSLog(@"gsDidReceiveResponse:\nMethod=%@\nResponse=%@\n context=%@",method,resMsg,context);
}

 

Step 3 - pass your delegate as the third parameter of the sendRequest method:
// in this example 'self' conforms to the GSResponseDelegate protocol 
[gsAPI sendRequest:@"socialize.setStatus" params:pParams delegate:self context:nil]

 

The gsDidReceiveResponse method receives a GSResponse object. The GSResponse object includes data fields. For each request method, the response data fields are different. Please refer to the Gigya REST API reference for the list of response data fields per method.

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

- (void) gsDidReceiveResponse:(NSString*)method response:(GSResponse*)response context:(id)context
{
        // Handle response here...
        if (response.errorCode==0) {  // SUCCESS! response status = OK			
                NSString * nickname = [response.data getString:@"nickname"];
                NSString * age = [response.data getString:@"age"];
	        NSLog(@"User name: %@\nThe user's age: %@\n", nickname, age);
	} else {
		NSLog(@"Got error on getUserInfo: %@", response.errorMessage);
	}
        
}

 

 

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 compound GSObjects or a JSON string, as shown in the two examples below:

 

Option A - Using GSObject's put Method

// 1. Defining request parameters
GSObject *userAction =[[GSObject alloc] init];

[userAction putStringValue:@"This is my title" forKey:@"title"]; 
[userAction putStringValue:@"This is my user message" forKey:@"userMessage"]; 
[userAction putStringValue:@"This is my description" forKey:@"description"]; 
[userAction putStringValue:@"http://gigya.com" forKey:@"linkBack"]; 

GSObject *image = [[GSObject new] autorelease];   // create a media item of type image to add to the user action
[image putStringValue:@"http://www.infozoom.ru/wp-content/uploads/2009/08/d06_19748631.jpg" forKey:@"src"]; 
[image putStringValue:@"http://www.gigya.com" forKey:@"href"]; 
[image putStringValue:@"image" forKey:@"type"]; 

NSArray *mediaItems = [NSArray arrayWithObject:image];  // create media items array and add the image object to it

[userAction putNSArrayValue:mediaItems forKey:@"mediaItems"]; 

GSObject *pParams = [[GSObject alloc] init];

[pParams putGSObjectValueGSObjectGSObject:userGSObjectiuserAuserActioneforKeyerAuserActionserAuserActiuserAuserActionametering 'socialize.publishUserAction' request
[gsAPIgsAPIRsendRequestcialize.publishUserAction" paramparamsapParamsgate:npParamsext:nil];

[userAuserActiuserAuserActionaseamsapParapParamsasepParams

 

Option B - Using a JSON String

// 1. Defining request parameters 
NSString *actionStr = @"{\"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\"}]}";
	
GSObject *userAction = [GSObject objectWithJSONString:actionStr];
	
GSObject *pParams = =[[GSObject alloc] init];
[pParams putGSObjectValueGSObjectGSObject: useGSObjecttiuserAuserActioneforKeyerAuserActionuserActionserAuserAcuserAction 


// 2. SeuserAuserActionameteruserActionishUserAction' request
[gsAPIgsAPIRsendRequestcialize.publishUserAction" paramparamsapParamsgate:nil context:nil]; 

[pParappParamsse];pParapParamsasepParams

 

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

 

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:

Mobile_siteLogin.gif

 

  • 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 GSAPI.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 sessionSecret:sessionSecret expirationTime:expirationTime] autorelease];
    [gsAPI 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.

 

 

Adding Facebook Single Sign-on

iOS enables users to set their Facebook account on their device. iOS applications can access the native account to authenticate the user without requiring the user to enter their credentials. Utilizing this functionality on your app, your users will have one-click login access to all participating platform applications on their mobile phone. 

Note: If you want certain permissions, you must ask for them explicitly, using Facebook's permission strings as defined in Facebook's documentation.

Follow these steps to utilize Facebook single sign-on for iOS:

  1. Bind your application to a URL scheme corresponding to your Facebook application ID. The URL scheme you must bind to is of the format "fb[appId]://", where [appId] is your Facebook application ID. Without this, your application will not be able to handle authorization callbacks. Modify your application's .plist file as follows:
    • Under the root key ("Information Property List") add a new row and name the key "URL types".
    • Under the "URL types" key that you just added, you should see a key named "Item 0". If not, add a new row with key "Item 0".
    • Under the "Item 0" key, add a new row and name the key "URL Schemes".
    • Under the "URL Schemes" key that you just added, you should see a key named "Item 0". If not, add a new row with key "Item 0".
    • Set the value of "Item 0" to "fb[appId]" where [appId] is your Facebook application ID. Make sure there are no spaces anywhere in this value. For example, if your application's id is 1234, the value should be "fb1234".
       
  2. Add the following to your app's code:
    //////////////////////////////////////////////////////////////////////////////////////////////////////////
    // This function will be called in future releases of iOS, but existing applications do not call it, and specifically - Facebook
    //////////////////////////////////////////////////////////////////////////////////////////////////////////
    - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
    {
      if(viewController.gsAPI != nil)
        return [viewController.gsAPI handleOpenURL:url];
      return NO;
    }
    //////////////////////////////////////////////////////////////////////////////////////////////////////////
    // This function will be deprecated in the future, but the current version of Facebook calls this function
    //////////////////////////////////////////////////////////////////////////////////////////////////////////
    - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
    {
      if(viewController.gsAPI != nil)
        return [viewController.gsAPI handleOpenURL:url];
      return NO;
    }

     

  3. When calling showLoginUIshowAddConnectionsUIlogin or addConnection, pass your Facebook's app ID as follows:
    GSObject *pParams = [[GSObject alloc] init];
    [pParams putStringValue:@"YOUR_FB_APP_ID" forKey:@"facebookAppId"];
    [gsAPI showLoginUI:pParams delegate:self context:nil];
    [pParams release];

    If you have multiple facebook apps using the same facebook app ID, please pass the facebook local app ID (facebookLocalAppId parameter) to these methods as well. In such case, you should also concat the local app ID to the app ID in the .plist file, as required by facebook. 

 

Adding Twitter Single Sign-on

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

Notes:

  • If there is more than one Twitter account available on the device, Gigya will choose the first one.
  • If there is no logged in twitter user, Gigya will use the regular webview login rather than the twitter SSO.

 

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 "accessToken" and "secret" from the getSession method of GSSession in your mobile SDK.
  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 SDK's SigUtils.validateUserSignature() method, passing in the data you received from step 1 and your Gigya secret key.
     

Demo Xcode Project

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

Download the Gigya Demo Project

In order for you to run the project on your own environment, please edit AppDelegate.m file and Change the "INSERT-YOUR-API-KEY-HERE" string to your own Gigya Api Key (please refer to Gigya Setup - Obtain Your Gigya API Key section above).

About the Demo

The demo UI includes a "Show Gigya Login UI" button. Clicking the button Gigya's Social Login UI appears (See screenshot under Logging in the User). You can click your prefered social network button to login.

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

The project includes the following Gigya related code:

  • In AppDelegate.h
    GSAPI* gsAPI; // Define the instance of the GSAPI class, which provides access to the Gigya service.
  • In AppDelegate.m
    // Initialize the instance of the GSAPI class, which provides access to the Gigya service.
    // (Change "INSERT-YOUR-API-KEY-HERE" to your Gigya Api Key, which can be obtained on https://platform.gigya.com/Site/partners/Dashboard.aspx)
    self.gsAPI = [[GSAPI alloc] initWithAPIKey:@"INSERT-YOUR-GIGYA-API-KEY-HERE"];
  • In ViewController.m
    // Show Gigya's Social Login UI
    GSObject* pParams = [[GSObject alloc] init];
    [pParams putStringValue:@"facebook,twitter,google" forKey:@"enabledProviders"];
    [app.gsAPI showLoginUI:pParams ViewController:self delegate:nil context:nil];
    [pParams release];
Was this article helpful?
Pages that link here
Page statistics
12097 view(s) and 32 edit(s)
Social share
Share this page?

Tags

This page has no custom tags set.

Comments

You must to post a comment.

Attachments