Was this article helpful?

iOS

Last modified 05:15, 15 Oct 2014

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

Note: Gigya's iOS SDK requires iOS 6.0 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.

 

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 

Please 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:

mobile_permissions.gif

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.
 

  1. Import the Gigya SDK header:
#import <GigyaSDK/Gigya.h>

 

  1. Add the following to your app's AppDelegate:
    - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
    {
        return [Gigya handleOpenURL:url 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

iOS_objC.gif

  1. In your app's Info tab, add a URL type and enter your bundle ID as the identifier and scheme:
    url_types.gif
 
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"];

Note: You should only call initWithAPIKey once.

 

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 logging-in is using one of the showLoginProvidersDialog methods of class Gigya. The methods open a login user interface, which present a selection of providers' icons, enabling the user to login via his social network / webmail account. Here is a screenshot of the login dialog:

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

iPhone-LoginUI.png

 

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 {
            // 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
    completionHandler:^(GSUser *user, NSError *error) {
        if (!error) {
            // Login was successful
        }
        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 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.

 

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 login 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 3.19  to your project.

  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

  1. Create an array key called URL types with a single array sub-item called URL SchemesGive 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".


iOS3.png

 

  1. 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
         completionHandler:^(GSUser *user, NSError *error) {
             if (!error) {
                 // Login was successful
             }
             else {
                 // Handle error
             }
         }];

 

  1. 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
  1. 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.
  1. If you want to ask the user for additional permissions, you need to use the Gigya class requestNewFacebookPublishPermissions or requestNewFacebookReadPermissions methods. 

 

Adding Google+ Native Login

Gigya's SDK allows you to use the native login feature from the Google+ SDK. Utilizing this functionality on your app, your users will be able to authenticate through the Google+ iOS app. 

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

Follow these steps to utilize the Google+ native login for iOS:

  1. Add the Google+ iOS SDK 1.5 to your project.
  1. Add the following frameworks to your project:
  • AddressBook.framework​​
  • AssetsLibrary.framework
  • CoreLocation.framework
  • CoreMotion.framework
  • CoreGraphics.framework
  • CoreText.framework
  • MediaPlayer.framework
  • Security.framework
  • SystemConfiguration.framework

iOS_SystemConfiguration.gif

  1. Add the following parameter to your app's .plist file:

  • GooglePlusClientID - your client ID 

  1. In your app's Info tab, add a URL type and enter your bundle ID as the identifier and scheme:

     File:035_Mobile_SDKs/010_iPhone/clipboard_1370764252289.png

     

  1. 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
         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.
  1. 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 Twitter.framework and Accounts.framework to your project:

iOS.bmp

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

 

Integrating Your Site with the iOS SDK

GSWebBridge connects between the Gigya JavaScript SDK and 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 in the JS SDK.
  • Any API requests by the JS SDK will be routed through the iOS SDK, using the iOS SDK session.
  • Any login process 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.

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

 

Using Gigya Plugins in the iOS SDK

GSPluginView is a custom UIView that renders Gigya JS Plugins and integrates them seamlessly with the GigyaiOS 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.

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

 

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:

iOS_login.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 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​Edit section

As user sessions can expire from 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 isValid for the current user session:

if ([[Gigya session] isValid]) {
    // 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.
     

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

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

Was this article helpful?
Pages that link here
Page statistics
878 view(s) and 8 edit(s)
Social share
Share this page?

Tags

This page has no custom tags.

Comments

You must to post a comment.

Attachments