Gigya Job Openings

Swift SDK

Skip to end of metadata
Go to start of metadata

Description

This document is a practical step-by-step guide for integrating & utilizing Gigya's services within the extent of your iOS Swift native application.

Code examples will be provided in Swift.


Why should I upgrade?

Gigya's Swift SDK v1 is a complete redesign of the previous Objective C SDK.
When we approached the redesign, we first consulted the developers that experienced implementation of the old SDK in their mobile app and together we defined 3 leading aspects to the new one:

  1. Aligned with up-to-date development and performance standards
  2. Great customer development experience (never leave the IDE)
  3. Focus on common business flows

so in Gigya's Swift SDK v1, you'll enjoy the benefits of:

  1. Better performance.
  2. Easy work with you site's custom account schema as it's now easily integrated with the entire SDK.
  3. Caching of the end-user's account data to reduce network calls.
  4. Built-in business flows, like registration, login and more, with out-of-the-box handling for the different outcome scenarios.
    1. For example, an end-user tries to register and gets "pending registration" due to a missing required field configured in the site's schema.

 

Download

Download the latest Swift SDK files:

Gigya Developer Downloads

 

Sample Application

A sample application which contains most available features is available for download in Swift.

Gigya Developer Downloads

 

Basic Integration

In order to integrate the Swift SDK into your project, please download and add the following .framework files to your Embedded Binaries and Linked Frameworks and Libraries sections:

  • Gigya.framework
  • GigyaInfra.framework

 

Initialization

The SDK requires an active reference to the running AppDelegate.swift, for example:

import GigyaSwift
  
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    /*
    Initializing the SDK. Account schema will be set to GigyaAccount struct.
    */
    GigyaSwift.sharedInstance()
  
    /*
    Initializing the SDK with a custom account schema.
    */
    GigyaSwift.sharedInstance(MyAccount.self)
  
    return true
}

When you using custom account schema you need include it every time you are using GigyaSwift.sharedInstance.

 

Implicit Initialization

The SDK will implicitly initialize itself according to Info.plist configuration.

Add the following two key/values to your app's .plist file:

  • GigyaApiKey: your Gigya key
  • GigyaApiDomain (optional): Data center, default is us1.

    See Finding Your Data Center to determine your data center.

 

 

Explicit Initialization

As an alternative to implicit initialization, you can initialize the SDK explicitly:

/*
Using default domain (us1-gigya.com).
*/
GigyaSwift.sharedInstance().initWithApi(apiKey: "YOUR-API-KEY")
  
/*
Supplying Api-Key & Api-Domain
*/
GigyaSwift.sharedInstance().initWithApi(apiKey: "YOUR-API-KEY", apiDomain: "YOUR-API-DOMAIN")

From this point, code blocks will use the Gigya interface as member variable (gigya), as if it was already initialized.

 

Sending a Request

You can send anonymous requests to Gigya using the SDK using one of two overloads:

  • General - this will return an dictionary (see the section below on how to access its data).
  • Typed - this will return an instance of the provided class.

The following example sends an "accounts.verifyLogin" request using the current logged in user's UID field to verify that the current session is still valid.

/*
Setup a map of parameters.
*/
let params = ["UID": "YOUR-ACCOUNT-UID"]
/*
Sending "verifyLogin" REST api.
*/
let api = "accounts.verifyLogin";
  
/*
Send a POST request. Will receive a general purpose Dictionary object in the success block.
*/
gigya.send(api: api, params: params) { (result) in
    switch result {
    case .success(let data):
        // Success - data is Dictionary
    case .failure(let error):
        break
    }
}
  
/*
Send a typed POST request. Will receive parsed MyAccount object in the success block.
*/
gigya.send(dataType: MyAccount.self, api: api, params: params) { (result) in
    switch result {
    case .success(let data):
        // Success - data is MyAccount
    case .failure(let error):
        break
    }
}

You can find the list of available Gigya API endpoints and their required parameters in the REST API Reference.

 

GigyaApiResult Enum with Associated Values

The SDK provides a custom response enum for encapsulating Gigya API's responses. 

This Enum exposes multiple cases that can help simplify your flow.

Here are a few examples of  a given response:

/*
Switch result (GigyaApiResult Enum) - return in all api requests
*/
switch result {
case .success(let data):
    // Success - data can be your custom schema or dictionary
case .failure(let error):
    // Failure - error is a another Enum, example:
        switch error {
        case .gigyaError(let data):
            // data is GigyaError
        case .providerError(let data):
            // data is an error from privider (String)
        case .networkError(let error):
            // error is an network error
        case .jsonParsingError(let error):
            // error is an error from json parsing ( when the json parsing fail )
        case .emptyResponse:
            // unknown error
        }
}

 

Login & Registration

Site login & registration via API calls (to differ from social login & registration) is available using the login/register methods.

Site Login & Registration

Here are a few examples for login/register usage:

Login via loginID & password:

gigya.login(loginId: "LOGIN-ID", password: "PASSWORD") { result in
    switch result {
    case .success(let data):
        // Success
    case .failure(let error):
        // Fail
    }
}

Register via email & password:

/*
Registering with a custom session expiration parameter.
*/
  
let params = ["sessionExpiration": expiration!] as [String : Any]
gigya.register(email: "email", password: "password", params: params) { result in
    switch result {
    case .success(let data):
        // Success
    case .failure(let error):
        // Fail
    }
}

 

Social Login

Logging-in using a social network is one of the key features of the Gigya Swift SDK.

The following social providers currently support the login operation:

  • Amazon
  • Blogger
  • Facebook
  • FourSquare
  • GooglePlus
  • Instagram
  • Kakao
  • LINE
  • LinkedIn
  • Livedoor
  • Messenger
  • mixi
  • Naver
  • Netlog
  • Odnoklassniki
  • Orange France
  • PayPalOAuth
  • Tencent QQ
  • Renren
  • Sina Weibo
  • Spiceworks
  • Twitter
  • VKontakte
  • WeChat
  • WordPress
  • Xing
  • Yahoo
  • Yahoo Japan

All supported providers constants are available using GigyaSocialProviders enum.

The following providers support native login using their own SDKs: Facebook, Google, Line, WeChat.

Please make sure to follow each configuration implementation mentioned in the "Configuring Native Login" section.

Having native support will require you to add the provider's library dependency to your application.

 

Provider Selection Screen

You can show a dialog with defined social providers in the following way:

/*
Show providers selection UI for selected providers
*/
gigya.socialLoginWith(providers: [.facebook, .google, .line], viewController: self, params: [:]) { (result) in
    switch result {
    case .success(let data):
        // Success
    case .failure(let error):
        // Fail
    }
}

Here is a screenshot using the above implementation:

 

 

Login With A Specified Provider

Alternatively, you can initiate social login flow to a specific social provider:

/*
Sign in with Facebook.
*/  
gigya.login(with: .facebook, viewController: self ) { [weak self] result in
    switch result {
    case .success(let data):
        // Success
    case .failure(let error):
        // Fail
    }
}

 

Configuring Native Login

For some social providers, the SDK supports social login via the social provider's native implementation. 

It is done by using the provider's native SDK, so it will require you to add its required libraries and wrappers to your Swift project.

We will review the relevant providers and their implementation flow.

Facebook

Adding Facebook native login to your iOS app is mandatory if you want to login via Facebook. To do so, set up your Facebook app in your XCode project using the following instructions:

If you do not yet have an active Facebook app please see our Facebook documentation.

For mobile specific, please go to Facebook Mobile App Setup.

Instructions for adding Facebook SDK to your iOS device can be found at Facebook SDK for iOS.

After completing to add the Facebook SDK to your project you need to import "FacebookWrapper.swift" file from "GigyaProviders" dictionary to your Xcode project.

Google 

Using Google Sign-In is mandatory if you want users to login via Google.

Instructions for adding Google Sign-in to your iOS device can be found at Google Sign-In for iOS.

Add the following tag to your plist file. It is recommended that the "GoogleClientID" String and "GoogleServerClientID" be placed in the your Info.plist file.

GoogleClientID: <Web application key from google console>
GoogleServerClientID: <iOS key from google console>

After you have completed to add Google Sign-in to your project you need to import "GoogleWrapper.swift" file from "GigyaProviders" dictionary to your Xcode project.

Line

The Gigya Swift SDK allows you to enable LINE native login for users that have the LINE app installed.

Instructions for adding LINE Native Login to your Android device can be found at Integrating LINE Login with an iOS app.

After you have completed to add Line SDK to your project you need to import "LineWrapper.swift" file from "GigyaProviders" dictionary to your Xcode project.

WeChat

The Gigya Swift SDK allows you to enable WeChat native login for users that have the WeChat app installed.

Instructions for adding WeChat to your iOS device can be found at WeChat for iOS.

Add the following tag to your plist file, It is recommended that the "WeChatAppID" String be placed in the your Info.plist file.

MISSING?

After you have completed to add WeChat SDK to your project you need to import "WeChatWrapper.swift" file from "GigyaProviders" dictionary to your Xcode project.

Notes:

  • The signature generation tool must be installed on the mobile device.
  • You will not be able to test WeChat functionality using an emulator. WeChat requires a physical mobile device.
  • Once you update your app signature in the WeChat console, it could take a couple of hours to update.
  • If you experience problems and notice errCode -6 from WeChat while debugging, it means the signature isn't correct.

 

Logout

A simple logout is available by using:

gigya.logout()

Logging out will clear all session data from the device.

Account Handling

 

Gigya's Swift SDK allows you to get a smooth developing experience by binding the SDK's main Gigya instance to a class of the same structure as your schema.

This will allow the SDK to accept and return account instances according to your specification.

Here is an example of a custom Account Schema struct, which corresponds with the above site's Schema.

struct MyAccount: GigyaAccountProtocol {
    var UID: String?
 
    var profile: GigyaProfile?
 
    var UIDSignature: String?
 
    var apiVersion: Int?
 
    var created: String?
 
    var createdTimestamp: Double?
 
    var isActive: Bool?
 
    var isRegistered: Bool?
 
    var isVerified: Bool?
 
    var lastLogin: String?
 
    var lastLoginTimestamp: Double?
 
    var lastUpdated: String?
 
    var lastUpdatedTimestamp: Double?
 
    var loginProvider: String?
 
    var oldestDataUpdated: String?
 
    var oldestDataUpdatedTimestamp: Double?
 
    var registered: String?
 
    var registeredTimestamp: Double?
 
    var signatureTimestamp: String?
 
    var socialProviders: String?
 
    var verified: String?
 
    var verifiedTimestamp: Double?
 
    var data: MyData?
}
  
struct MyData: Codable {
    var subscribe: Bool?
    var terms: Bool?
    var comment: String?
}

When you inherit from GigyaAccountProtocol, the relevant profile fields will be inherited and you can add the data field according to your schema.

We can initialize a Gigya instance with the MyAccount struct, and see the account methods operate accordingly.

Get Account

In order to retrieve the current account you can use the "getAccount" method:

gigya.getAccount() { result in
    switch result {
    case .success(let account):
        // Success
        print(account.profile)
    case .failure(let error):
        // Fail
    }
}

Using "getAccount" requires you to have a valid session.

In order to improve the end-user's experience by avoiding unnecessary network requests, the SDK caches the current account data for a period of 5 minutes (by default).

The account cache property can be set via the JSON configuration file or by adding a meta-data tag as show in the initializationsection of the document.

To bypass the account's caching you must provide true when requesting a new account:

gigya.getAccount(true) { result in
    switch result {
    case .success(let account):
        // Success
        print(account.profile)
    case .failure(let error):
        // Fail
    }
}

 

Set Account

The SDK provides two options for updating a user account data.

Using "setAccount" requires you to have a valid session.

In order to avoid unnecessary errors, please make sure that the fields you trying to update are marked as "client Modify" in the site's schema. You can verify this using Gigya's Admin Console, in your site's Schema Editor page under the Settings panel.

/*
Using live data to keep track of account object changes.
*/
gigya.setAccount(with: myAccountLiveData) { result in
    switch result {
    case .success(let account):
        // Success
        print(account.profile)
    case .failure(let error):
        // Fail
    }
}

Using Screen-Sets

Screen-Sets, as one of Gigya's most powerful features, are available also on your mobile app!

The SDK provides a simple interface for using & displaying screen-sets via the PluginViewController & the GigyaPluginEvent components.

ShowScreenSets method

Using screen-sets is available using the "showScreenSet" method of the Gigya interface.

Here is an example of using the SDK's showScreenSet method using the default "Registration-Login" screen set:

/*
Showing "Registration-Login" screen set in a dialog mode. Use only the onLogin case to be notified when logging in event was fired.
*/
 
gigya.showScreenSet(with: "Default-RegistrationLogin", viewController: self) { result in
    switch result {
    case .onLogin(let account):
        // Login success.
    default:
        break
    }
}

The "showScreenSets" method available parameters include all the parameters the web screen-sets plugin can receive.

 

GigyaPluginEvent Enum

This return object is an enum which is aligned to all optional plugin events fired by the screen-sets plugin.

Here is the Enum to its extent. You can use separate case by add default to the switch case:

switch result {
case .onLogin(let account):
    // onLogin event
case .onBeforeValidation(let event):
    // onBeforeValidation event
case .onBeforeSubmit(let event):
    // onBeforeSubmit event
case .onSubmit(let event):
    // onSubmit event
case .onAfterSubmit(let event):
    // onAfterSubmit event
case .onBeforeScreenLoad(let event):
    // onBeforeScreenLoad event
case .onAfterScreenLoad(let event):
    // onAfterScreenLoad event
case .onFieldChanged(let event):
    // onFieldChanged event
case .onHide(let event):
    // onHide event
case .onLogout:
    // onLogout event
case .onConnectionAdded:
    // onConnectionAdded event
case .onConnectionRemoved:
    // onConnectionRemoved event
case .error(let event):
    // error event
}

The plugin event is also typed to the current Account schema.

Business APIs

The Gigya SDK provides popular built-in flows for fluent development.

Currently available:

  • login
  • register
  • logout
  • verifyLogin
  • getAccount
  • setAccount
  • forgotPassword
  • addConnection
  • removeConnection

 

Business APIs are provided in order to give you an easier interface. If a more detailed and customized use is required, you can still use the generic Gigya.send interface for all request purposes.

Interruptions

Some flows can be "interrupted" due to certain Site policies.

For example, when trying to register but Two Factor Authentication is required - then an "interruption" can occur about "pending TFA registration" that will require the end user to setup a TFA method before being able to complete the registration flow.

Interruptions map:

 

The SDK's Business APIs are design to help to easily develop a friendly way to face and resolve those interruptions in order to get the end user logged in and still complying to the site's policies.

Handling Interruptions

Interruption handling is a key feature introduced as of v1 of the Swift SDK.

The SDK will expose a resolver object for supported interruptions in order to give you as a developer the ability to resolve them within the same flow that they were triggered.

The current supported interruption flows are:

  • Pending registration
  • Account linking
  • Pending TFA registration.
  • Pending TFA verification

All interruption flows are implemented in the provided Sample project.

Interruptions handling - Account linking example

We will start with a simple register request for an email address that is already registered:

gigya.register(email: "EMAIL-ADDRESS-ALREADY-REGISTERED", password: "PASSWORD") { result in
    switch result {
    case .success(let data):
        // Success
    case .failure(let error):
        // Fail
    }
}

As expected we will receive an error which indicates that this login identifier already exists in the system (errorCode 403043).

Usually when receiving that kind of error, we would trigger an API call to retrieve the conflicting accounts (via accounts.getConflictingAccount), then try to login with one of the supported account's identities (using mode:"link").

However, the SDK can handle this interruption for us:

To do so, in our our GigyaLoginResult we will switch the conflictingAccounts case:

gigya.register(email: "EMAIL-ADDRESS-ALREADY-REGISTERED", password: "PASSWORD") { result in
    switch result {
    case .success(let data):
        // Success
    case .failure(let error):
        // Fail
        guard let interruption = error.interruption else { return }
        // Evaluage interruption.
        case .conflitingAccount(let resolver):
            break
        default:
            break
    }
}

While the response parameter contains the original response from the register API call (accounts.register), the resolver object (of type LinkAccountsResolver) already contains all we need in order to complete the flow:

We can get the conflicting accounts from it and try to link the account to them.

 

let accounts = resolver.conflictingAccount
let providers = accounts?.conflictingAccount
let loginID = accounts?.loginID
  
/*
In this example the providers list contains one "site" provider. Therefore we are now able to try and resolve the flow.
*/ 
resolver.linkToSite(loginId: loginID, password: "PASSWORD-REQUIRED-TO-VERIFY-THE-ORIGINAL-ACCOUNT")
Trying the resolve the flow will now try to login with the original conflicted account and link both accounts. 
If the operation was successful, the original GigyaLoginResult will be notified and the flow will be directed to its original successcase.

In order to provide the end user with a fluid experience some UI intervention is recommended. Examples for this can be found in the Sample application.

FAQ

General

 What is the minimum Xcode Version supported by Gigya's Swift SDK (v1)?

 Gigya Swift SDK requires Xcode 10.2 and above.

 What is the minimum Swift version supported by Gigya's Swift SDK (v1)?

Gigya Swift SDK requires Swift 5 and above.

 Is Gigya's Swift SDK v1 compatible with Objective c version releases?

Upgrading application from Objective c to Swift SDK is supported (Only in Swift project) . Migration of your application code is required

 

 

 

 

 

 

 

 

.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

.

  • No labels