Account Kit for iOS

To set up Account Kit in your iOS app, follow these steps:

1. Prerequisites

2. Configure the SDK

3. Initialize the SDK

4. Configure Login View Controller

5. Handle Different Login States

6. Initiate a Login Flow for SMS

7. Initiate a Login Flow for Email

8. Handle Login Callback

9. Access Account Information

10. Provide the Logout Flow


Also see Next Steps for optional customizations you can perform.

For an example project that illustrates how to integrate Account Kit, see Account Kit Samples for iOS on GitHub.

For common issues encountered during integration, see the FAQ section.

1. Prerequisites

Before you begin integrating Account Kit into your app, make sure you have completed the following prerequisites.

A. Create a Developer Account

If you don't have a Facebook developer account, create one by clicking the button below.

Your Facebook developer account gives you access to developer tools and allows you to create Facebook apps.

Already have a Facebook developer account? Skip to the next step.

Create Developer Account

B. Get a Facebook App ID

Account Kit for iOS requires a Facebook app ID. Follow the steps in the Getting Started, or to use Quick Start, click the button below.

Create a New App ID

C. Choose Your App Settings

Choose whether to allow email and SMS login, and choose security settings for your app. For more information on choosing your acesss token setting, see Access Tokens, and for information on choosing your app secret setting, see Using the Graph API.

Choose Your App Settings

D. Download the Account Kit SDK

Download the latest Facebook SDK for iOS and use it to integrate your app with Account Kit.

Overview: The iOS SDK provides View Controllers which you can present to initiate the SMS or Email login flows.

Download the iOS SDK

2. Configure the SDK

Add Facebook app ID and Account Kit client token to Info.plist

Add both your Facebook App ID and Account Kit Client Token to your Info.plist file as strings. Make sure you have enabled Account Kit in the App Dashboard. You'll find the Account Kit client token in the Account Kit section of the App Dashboard. The application name will be used in the UI on the login screen.

<plist version="1.0">
<dict>
  <key>FacebookAppID</key>
  <string>{your-app-id}</string>
  <key>AccountKitClientToken</key>
  <string>{your-account-kit-client-token}</string>
  <key>CFBundleURLTypes</key>
  <array>
    <dict>
      <key>CFBundleURLSchemes</key>
      <array>
        <string>ak{your-app-id}</string>
      </array>
    </dict>
  </array>
  ...
</dict>
</plist>

If you wish to disable App Events for your Account Kit application, add the following entry to your Info.plist file inside the <dict> tag:

<key>AccountKitFacebookAppEventsEnabled</key>
<integer>0</integer>

By default, this flag is set to 1. See App Events and Analytics for more information.

Link Account Kit Framework

From the SDK, drag and drop AccountKit.framework and AccountKitStrings.bundle to link them to your iOS project.

3. Initialize the SDK

In your initial view controllers, import the Account Kit headers and declare an _accountKit variable to manage all Account Kit interactions. Declare the view controller to be an implementer of AKFViewControllerDelegate.

#import <AccountKit/AccountKit.h>

@interface LoginViewController () <AKFViewControllerDelegate>
@end

@implementation LoginViewController
{
  AKFAccountKit *_accountKit;
  UIViewController<AKFViewController> *_pendingLoginViewController;
  NSString *_authorizationCode;
}

When your initial view controller is loaded, check and initialize your _accountKit variable. Be sure the response type you use to initialize Account Kit matches the one selected in your app's dashboard in the Facebook developer portal, either AKFResponseTypeAccessToken or AKFResponseTypeAuthorizationCode.

- (void)viewDidLoad
{
  [super viewDidLoad];

  // initialize Account Kit
  if (_accountKit == nil) {
    // may also specify AKFResponseTypeAccessToken
    _accountKit = [[AKFAccountKit alloc] initWithResponseType:AKFResponseTypeAuthorizationCode];
  }

  // view controller for resuming login
  _pendingLoginViewController = [_accountKit viewControllerForLoginResume];
}

4. Configure Login View Controller

You can configure your Login View Controller with the following parameters:

ParameterDescription

delegate

AKFViewControllerDelegate*: Pass in the delegate handling the login callback.

advancedUIManager

AKFAdvancedUIManager*: Pass in a class implementing AKFAdvancedUIManager if you would like to use the Advanced UI. Otherwise you can pass in nil. For more information, see Customizing the UI.

theme

AKFTheme*: Pass in a theme for the login view. Otherwise you can pass in nil for the default theme.

Prepare the Account Kit login view controller by setting a delegate as shown in the following code block. Here we are also applying bicycleTheme to the Login view:

- (void)_prepareLoginViewController:(UIViewController<AKFViewController> *)loginViewController
{
  loginViewController.delegate = self;
  // Optionally, you may use the Advanced UI Manager or set a theme to customize the UI.
  loginViewController.advancedUIManager = _advancedUIManager;
  loginViewController.theme = [Themes bicycleTheme];
}

The delegate for your loginViewController must implement the AKFViewControllerDelegate protocol. All of the protocol methods are optional, but you should at least handle successful login callbacks for the login flows (SMS or Email) that you use in your app.

UI Theming

You can create bicycleTheme with the following code:

+ (AKFTheme *)bicycleTheme
{
  AKFTheme *theme = [AKFTheme outlineThemeWithPrimaryColor:[self _colorWithHex:0xffff5a5f]
                                          primaryTextColor:[UIColor whiteColor]
                                        secondaryTextColor:[UIColor whiteColor]
                                            statusBarStyle:UIStatusBarStyleLightContent];
  theme.backgroundImage = [UIImage imageNamed:@"bicycle"];
  theme.backgroundColor = [self _colorWithHex:0x66000000];
  theme.inputBackgroundColor = [self _colorWithHex:0x00000000];
  theme.inputBorderColor = [UIColor whiteColor];
  return theme;
}

+ (UIColor *)_colorWithHex:(NSUInteger)hex
{
  CGFloat alpha = ((CGFloat)((hex & 0xff000000) >> 24)) / 255.0;
  CGFloat red = ((CGFloat)((hex & 0x00ff0000) >> 16)) / 255.0;
  CGFloat green = ((CGFloat)((hex & 0x0000ff00) >> 8)) / 255.0;
  CGFloat blue = ((CGFloat)((hex & 0x000000ff) >> 0)) / 255.0;
  return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
}

You may apply a theme or use the Advanced UI Manager if you want to customize the user interface. For more information, see Customizing the UI.

5. Handle Different Login States

When your initial view controller appears, the code below will bypass the login view controller if the user is already logged in. It will also resume pending logins.

- (void)viewWillAppear:(BOOL)animated
{
  [super viewWillAppear:animated];

  if ([self isUserLoggedIn]) {
    // if the user is already logged in, go to the main screen
    [self proceedToMainScreen];
  } else if (_pendingLoginViewController != nil) {
    // resume pending login (if any)
    [self _prepareLoginViewController:_pendingLoginViewController];
    [self presentViewController:_pendingLoginViewController 
                       animated:animated 
                     completion:NULL];
    _pendingLoginViewController = nil;
  }
}

If your app receives the user's access token directly (because the Enable Client Access Token Flow switch in your app's dashboard is ON), then you should check for a valid, existing token in isUserLoggedIn, using [_accountKit currentUserToken].

If your app receives an authorization code that it will pass to the server (because the Enable Client Access Token Flow switch in your app's dashboard is OFF), it is up to you to have your server communicate the correct login status to your client application and return that in isUserLoggedIn.

For more information on access tokens and authorization codes, see Access Tokens and Authorization Codes.

6. Initiate a Login Flow for SMS

In your initial view controller, create a phone login handler to invoke when the login button is clicked by the user. There are three important parameters shown in the code below:

ParameterDescription

preFillPhoneNumber

nullable NSString*: Pass this to pre-fill the phone number field in the phone login flow. Use nil to skip pre-filling.

inputState

NSString*: This should be a random, non-guessable value. Any value passed via this parameter will be returned with the login response; compare the value in the response with this value to verify that the response you received was for the request you issued.

enableSendToFacebook

BOOL: If this flag is set to YES, the user has the option of receiving the login confirmation message via Facebook push notification, if the SMS send fails and if the phone number they entered is the primary phone number on their Facebook account. This flag defaults to NO.

- (void)loginWithPhone:(id)sender
{
  NSString *preFillPhoneNumber = nil;
  NSString *inputState = [[NSUUID UUID] UUIDString];
  UIViewController<AKFViewController> *viewController = [_accountKit viewControllerForPhoneLoginWithPhoneNumber:preFillPhoneNumber
                                                                                                          state:inputState];
  viewController.enableSendToFacebook = YES; // defaults to NO
  [self _prepareLoginViewController:viewController]; // see below
  [self presentViewController:viewController animated:YES completion:NULL];
}

7. Initiate a Login Flow for Email

In your initial view controller, create an email login handler to invoke when the login button is clicked by the user. There are two important parameters shown in the code below:

ParameterDescription

preFillEmailAddress

nullable NSString*: Pass this to pre-fill the email address field in the email login flow. Use nil to skip pre-filling.

inputState

NSString*: This should be a random, non-guessable value. Any value passed via this parameter will be returned with the login response; compare the value in the response with this value to verify that the response you received was for the request you issued.

- (void)loginWithEmail:(id)sender
{
  NSString *inputState = [[NSUUID UUID] UUIDString];
  UIViewController<AKFViewController> *viewController = [_accountKit viewControllerForEmailLoginWithEmail:preFillEmailAddress
                                                                                                    state:inputState];
  [self _prepareLoginViewController:viewController]; // see below
  [self presentViewController:viewController animated:YES completion:NULL];
}

8. Handle Login Callback

How you handle a login depends on whether your app uses an access token or an authorization code. For more information, see Access Tokens and Authorization Codes.

To handle a successful login in Access Token mode:

// handle callbacks on successful login to show account
- (void)           viewController:(UIViewController<AKFViewController> *)viewController
  didCompleteLoginWithAccessToken:(id<AKFAccessToken>)accessToken
                            state:(NSString *)state
{
  [self proceedToMainScreen];
}

To handle a successful login in Authorization Code mode:

// handle callback on successful login to show authorization code
- (void)                 viewController:(UIViewController<AKFViewController> *)viewController
  didCompleteLoginWithAuthorizationCode:(NSString *)code
                                  state:(NSString *)state
{
  // Pass the code to your own server and have your server exchange it for a user access token.
  // You should wait until you receive a response from your server before proceeding to the main screen.
  [self sendAuthorizationCodeToServer:code];
  [self proceedToMainScreen];
}

You may also handle a failed or canceled login:

- (void)viewController:(UIViewController<AKFViewController> *)viewController didFailWithError:(NSError *)error
{
  // ... implement appropriate error handling ...
  NSLog(@"%@ did fail with error: %@", viewController, error);
}

- (void)viewControllerDidCancel:(UIViewController<AKFViewController> *)viewController
{
  // ... handle user cancellation of the login process ...
}

9. Access Account Information

Once you have successfully logged in, you can access account information. For example, to display the account ID and the credential used to log in in access token mode:

AKFAccountKit *accountKit = [[AKFAccountKit alloc] initWithResponseType:AKFResponseTypeAccessToken];
[accountKit requestAccount:^(id<AKFAccount> account, NSError *error) {
  // account ID
  self.accountIDLabel.text = account.accountID;
  if ([account.emailAddress length] > 0) {
    self.titleLabel.text = @"Email Address";
    self.valueLabel.text = account.emailAddress;
  } 
  else if ([account phoneNumber] != nil) {
    self.titleLabel.text = @"Phone Number";
    self.valueLabel.text = [[account phoneNumber] stringRepresentation];
  }
}];

To display the account ID and the credential used to log in in Authorization Code mode, call your server to use the Graph API with the exchanged access token stored on your server (see Access Token Validation), and have your server pass the account ID and credential back to your app.

10. Provide the Logout Flow

You can invoke the logOut method to log a user out of Account Kit.

[accountKit logOut];