Integrating Facebook Accounts

This topic explains how to allow your users to sign up for and log in to your mobile app with their Facebook account. Just add a few parameters in the developer portal and a few lines of code in your mobile app and you will be social-ready!

Configuring Facebook integration

Creating a Facebook application

To get started, you first need to create a Facebook application and get your Facebook app ID and app secret. For the detailed instructions, see the Facebook official documentation.

You need to provide the following information. In the "Valid OAuth redirect URIs," please specify the value that corresponds to the server location you've selected (please put your AppID in ${your-app-id}).

  • Display Name
  • Namespace
  • Category
  • Valid OAuth redirect URIs (After creating the application, add "Facebook Login" in the Production section and select the "Settings")
    • United States: https://${your-app-id}.us.kiiapps.com/api/apps/${your-app-id}/integration/webauth/callback
    • Japan: https://${your-app-id}.jp.kiiapps.com/api/apps/${your-app-id}/integration/webauth/callback
    • Singapore: https://${your-app-id}.sg.kiiapps.com/api/apps/${your-app-id}/integration/webauth/callback
    • Europe: https://${your-app-id}.eu.kiiapps.com/api/apps/${your-app-id}/integration/webauth/callback

Configuring a Kii application

Take the following steps in the developer portal to configure your application by setting your Facebook app ID and app secret.

  1. Click on the "Edit" button in your application console in the developer portal.

  2. Click "SOCIAL NETWORKS".

  3. Click "Facebook" to open the configuration screen for Facebook.

  4. Set your Facebook app ID and app secret.

Logging in with a Facebook account

There are two ways to log in with a Facebook account.

The latter method (using the login UI) will be discontinued in near future. It is now outside of our support. Use the former method of using a Facebook access token.

Using a Facebook access token

The following example illustrates how to authenticate a user by using a Facebook access token.

Swift 3:

func myRegistrationMethod(){
  // Set a Facebook access token.
  let options : Dictionary = ["accessToken":accessToken]

  // Authenticate the user to Kii Cloud with the Facebook access token.
  KiiSocialConnect.log(in: .Facebook, options: options) { (retUser :KiiUser?, provider : KiiConnectorProvider, retError : Error? ) -> Void in
    if (retError != nil) {
      // Handle the error.
      return
    }
  }
}

Objective-C:

- (void)myRegistrationMethod {
  // Set a Facebook access token.
  NSDictionary *options = @{@"accessToken" : accessToken};

  // Authenticate the user to Kii Cloud with the Facebook access token.
  [KiiSocialConnect logIn:kiiConnectorFacebook
                  options:options
                    block:^(KiiUser *retUser, KiiConnectorProvider provider, NSError *retError) {
    if (retError != nil) {
      // Handle the error.
      return;
    }
  }];
}

The basic steps are as follows.

  1. Get a Facebook access token. For the detailed instructions, see Configuration and implementation example below. You can also see the Facebook official documentation.

  2. Set the Facebook access token to the accessToken parameter of options.

  3. Authenticate the user with the logIn:options:block: method. The first argument specifies the target social network, kiiConnectorFacebook. If the specified Facebook account is new to Kii Cloud, the user is registered before the login. The logIn:options:block: method is non-blocking and receives the processing result with the callback method.

If the login is successful, the user is cached inside the SDK as the current user and you can get the user information with the currentUser method. You can also retrieve the access token and related parameters with the accessTokenDictionary: method as follows:

Swift 3:

// Get the token dictionary for the social network provider.
let dict  = KiiSocialConnect.accessTokenDictionary(.Facebook)! as NSDictionary

// Get the access token.
let accessToken = (dict.object(forKey: "oauth_token") as? String)!

// Get the user ID provided by the social network provider.
let providerUserId = (dict.object(forKey: "provider_user_id") as? String)!

// Check if a new Kii user was created when the log(in:options:_:) method was executed.
let kiiNewUser : Bool = (dict.object(forKey: "kii_new_user") as? NSNumber)!.boolValue

Objective-C:

// Get the token dictionary for the social network provider.
NSDictionary *dict = [KiiSocialConnect accessTokenDictionary:kiiConnectorFacebook];

// Get the access token.
NSString *accessToken = [dict objectForKey:@"oauth_token"];

// Get the user ID provided by the social network provider.
NSString *providerUserId = [dict objectForKey:@"provider_user_id"];

// Check if a new Kii user was created when the logIn:options:block: method was executed.
BOOL kiiNewUser = [dict valueForKey:@"kii_new_user"];

Using the login UI provided by the SDK (Deprecated)

Here is the sample code for letting a new user log in with their Facebook account:

Swift 3:

func myRegistrationMethod(){
  // Set options to nil to indicate that SDK will handle the UI
  let options : Dictionary<String,AnyObject>? = nil

  //Login

  KiiSocialConnect.log(in: .Facebook, options: options) { (retUser :KiiUser?, provider : KiiConnectorProvider, retError : Error? ) -> Void in
    if (retError != nil) {
      // Handle the error.
      return
    }
    // The user has logged in successfully
  }
}

Objective-C:

- (void)myRegistrationMethod {
  // Set options to nil to indicate that SDK will handle the UI
  NSDictionary *options = nil;

  // Login.
  [KiiSocialConnect logIn:kiiConnectorFacebook
                  options:options
                    block:^(KiiUser *retUser, KiiConnectorProvider provider, NSError *retError) {
    if (retError != nil) {
      // Handle the error.
      return;
    }
    // The user has logged in successfully
  }];
}

The basic steps are as follows.

  1. Set nil to options to specify the authentication mechanism.
  2. Authenticate the user with the logIn:options:block: method. If the specified Facebook account is new to Kii Cloud, the user is registered before the login. The logIn:options:block: method is non-blocking and receives the processing result with the callback method.

Linking a Kii account to a Facebook account

You can link existing Kii users to their Facebook accounts. Linked users can log in to Kii Cloud via the Facebook authentication.

Here is the sample code for linking a Kii account to a Facebook account. You basically just need to execute the linkCurrentUser:options:block: method.

Note that this sample code assumes that your mobile app has obtained a Facebook access token. For getting a Facebook access token, see Configuration and implementation example below. You can also see the Facebook official documentation.

Swift 3:

// Assume that a user has logged in.

func myAccountLinkMethod(){
  // Set a Facebook access token.
  let options : Dictionary = ["accessToken":accessToken]

  // Link the Facebook account with the currently logged-in Kii user.
  KiiSocialConnect.linkCurrentUser(.Facebook, options: options) { (retUser :KiiUser?, provider : KiiConnectorProvider, retError : Error? ) -> Void in
    if (retError != nil) {
      // Handle the error.
      return
    }
  }
}

Objective-C:

// Assume that a user has logged in.

- (void) myAccountLinkMethod {
  // Set a Facebook access token.
  NSDictionary *options = @{
    @"access_token":accessToken
  }

  // Link the Facebook account with the currently logged-in Kii user.
  [KiiSocialConnect linkCurrentUser:kiiConnectorFacebook
                            options:options
                              block:^(KiiUser *retUser, KiiConnectorProvider provider, NSError *retError) {
    if (retError != nil) {
      // Handle the error.
      return;
    }
  }];
}

Unlinking a Kii account from a Facebook account

Here is the sample code for unlinking a Kii account from a Facebook account. You basically just need to execute the unLinkCurrentUser:options:block: method.

Swift 3:

// Assume that a user has logged in.

func myAccountUnlinkMethod(){
  // Unlink the Facebook account from the currently logged-in Kii user.
  KiiSocialConnect.unLinkCurrentUser(.Facebook) { (retUser :KiiUser?, provider : KiiConnectorProvider, retError : Error? ) -> Void in
    if (retError != nil) {
      // Handle the error.
      return
    }
  }
}

Objective-C:

// Assume that a user has logged in.

- (void) myAccountUnlinkMethod {
  // Unlink the Facebook account from the currently logged-in Kii user.
  [KiiSocialConnect unLinkCurrentUser:kiiConnectorFacebook
                                block:^(KiiUser *retUser, KiiConnectorProvider provider, NSError *retError) {
    if (retError != nil) {
      // Handle the error.
      return;
    }
  }];
}

Configuration and implementation example

This section briefly covers the steps for integrating Facebook account.

Getting a Facebook access token is out of the scope of Kii Cloud feature, so the steps covered in this section are just for your reference. These steps confirmed to work as of October 2017. Search general technical information on the Internet for the up-to-date and more detailed steps.

By following the steps below, you will be able to add a Facebook login button on your mobile app and to authenticate a user with his Facebook username and password. Once the user authentication is passed, your mobile app will get the user's Facebook access token. You can then use the token for leveraging Kii Cloud login and user linking functions, which are covered in the previous section of this page.

When checking articles on the Internet, be careful that some of them cover procedures for getting your (i.e., developer's) access token for auto-posting and such. For the integration with the Kii Cloud, you need to get an end user's access token.

Configuration on Facebook admin screen

The configuration is made in "facebook for developers".

  1. Open facebook for developers on your web browser and login.

  2. Select "Add a New App", or select the existing Facebook app.

  3. Run the iOS "Quickstart".

    If you have not selected iOS as the platform yet, start the Facebook SDK quickstart on the "Dashboard" screen by clicking the "Choose Platform" button and select "iOS" as the platform.

    If you have already selected iOS as the platform, select "Settings" - "Basic" and click the "Quick Start" button in the "iOS" section.

  4. Follow the instructions in the quickstart and make the following configurations.

    We will later provide a sample code, so you can ignore the code in "Let's test out your integration".

    • Download the Facebook SDK and add the framework specified in the instruction to your project.
    • Open the Info.plist as a XML souce code and add the designated tag. Also add the LSApplicationQueriesSchemes key since we will use a dialogue in the login process.
    • Enter the Bundle Identifier in the Facebook configuration screen.
    • Add the initialization code in the AppDelegate. If you are using Swift, you need to port the code from Objective-C.
  5. You will get the Facebook App ID and App Secret. Set them in the developer portal.

Program implementation

After making the configuration on the dashboard screen, add the following implementations in your mobile app:

  1. Update the class declaration of the view controller.

    Modify the target view controller to implement the FBSDKLoginButtonDelegate protocol.

    Swift 3:

    import FBSDKLoginKit
    import FBSDKCoreKit
    
    class ViewController: UIViewController, FBSDKLoginButtonDelegate {
      // ......
    }
    

    Objective-C:

    #import <FBSDKLoginKit/FBSDKLoginKit.h>
    #import <FBSDKCoreKit/FBSDKAccessToken.h>
    
    @interface ViewController : UIViewController <FBSDKLoginButtonDelegate>
    
    @end
    
  2. Add a button in the view.

    Add a Facebook button in the viewDidLoad() method.

    In the following sample code, the FBSDKAccessToken.current() will show the button when a user is not logged in to Facebook. Adjust the implementation to accommodate your mobile app specification.

    Swift 3:

    override func viewDidLoad() {
      super.viewDidLoad()
    
      if FBSDKAccessToken.current() == nil {
        let logInButton = FBSDKLoginButton()
        logInButton.center = self.view.center
        logInButton.delegate = self
        self.view.addSubview(logInButton)
      } else {
        let accessToken = FBSDKAccessToken.current().tokenString!
        // Add Kii Cloud login process here.
      }
    }
    

    Objective-C:

    - (void)viewDidLoad {
      [super viewDidLoad];
    
      if ([FBSDKAccessToken currentAccessToken] == nil) {
        FBSDKLoginButton *loginButton = [[FBSDKLoginButton alloc] init];
        loginButton.center = self.view.center;
        loginButton.delegate = self;
        [self.view addSubview:loginButton];
      } else {
        NSString* acccessToken = [FBSDKAccessToken currentAccessToken].tokenString;
        // Add Kii Cloud login process here.
      }
    }
    

    Note the button label will be "Continue with Facebook" for the Facebook SDK 4.19.0 and later. If you are using the earlier SDK version, the label will be "Log in with Facebook".

  3. Implement methods of the FBSDKLoginButtonDelegate protocol.

    Here, we implement the loginButton(_:didCompleteWith:error:) and loginButtonDidLogOut(_:) methods.

    Swift 3:

    func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
      if error != nil || result.isCancelled {
        return;
      }
      let accessToken = result.token.tokenString!;
      // Add Kii Cloud login process here.
    }
    
    func loginButtonDidLogOut(_ loginButton: FBSDKLoginButton!) {
    }
    

    Objective-C:

    - (void)loginButton:(FBSDKLoginButton *)loginButton didCompleteWithResult:(FBSDKLoginManagerLoginResult *)result error:(NSError *)error {
      if (error != nil || result.isCancelled) {
        return;
      }
      NSString* accessToken = result.token.tokenString;
      // Add Kii Cloud login process here.
    }
    
    -(void)loginButtonDidLogOut:(FBSDKLoginButton *)loginButton {
    }
    

When you are done with the implementation, run your mobile app. A Facebook login button should appear on the screen where you have put the button.

You will add the processes for handling Kii Cloud login and user linking in the places where the comment // Add Kii Cloud login process here. is set. The comment is set at the beginning of the view when a user is already logged in and in the callback that will be invoked when the Facebook login completes. You can use the Facebook access token accessToken in the processes.

The above sample only implements the basic feature for leveraging the access token. See the Facebook document for a complete implementation guide.