iOS Tutorial
(http://developers.facebook.com/docs/mobile/ios/build/#register)
This document will guide you through Facebook Platform integration for iOS. We will walk you through a tutorial to show the key steps to building a social iOS app. This will include showing you how to enable Single Sign-On. We will also cover additional topics around integrating with Facebook Platform.
Getting Started:
Adding Social Context:
Advanced Configuration:
Additional Topics:
Getting Started
Step 1: Registering your iOS App with Facebook
To begin integrating with the Facebook Platform,
Note your App ID. You are going to need it when setting up your app in Xcode.
You application is now set up and you’re ready to begin integrating with Facebook!
Step 2: Installing the iOS SDK
Before you begin development with the Facebook iOS SDK, you will need to install the iOS dev tools, Git (the source control client we use for this SDK) and then clone the latest version of the SDK from
-
Install
Xcode -
Install
Git -
Clone the
GitHub repository: git clone git://github.com/facebook/facebook-ios-sdk.git
Once you have everything installed you are now ready to set up your iOS app. First we will discuss Single Sign-On (SSO) which is a key implementation feature you should provide. After that section we will walk you through the steps of setting up an iOS app and enabling SSO.
Step 3: Implementing Single Sign-On (SSO)
One of the most compelling features of the iOS SDK is
SSO primarily works by redirecting the user to the Facebook app on her device. Since the user is already logged into Facebook, they will not need to enter their username and password to identify themselves. They will see the auth dialog with the permissions that your app has asked for and if they allow then they will be redirected to your app with the appropriate access_token
.
Developers should be aware that Facebook SSO will behave slightly different depending on what is installed on the user's device. This is what happens in certain configurations:
-
If the app is running in a version of iOS that supports multitasking, and if the device has the Facebook app of version 3.2.3 or greater installed, the SDK attempts to open the authorization dialog within the Facebook app. After the user grants or declines the authorization, the Facebook app redirects back to the calling app, passing the authorization token, expiration, and any other parameters the Facebook OAuth server may return.
-
If the device is running in a version of iOS that supports multitasking, but it doesn't have the Facebook app of version 3.2.3 or greater installed, the SDK will open the authorization dialog in Safari. After the user grants or revokes the authorization, Safari redirects back to the calling app. Similar to the Facebook app based authorization, this allows multiple apps to share the same Facebook user
access_token
through the Safari cookie. -
If the app is running a version of iOS that does not support multitasking, the SDK uses the old mechanism of popping up an inline UIWebView, prompting the user to log in and grant access. The
FBSessionDelegate
is a callback interface that your app should implement: The delegate's methods will be invoked when the app successful logs in or logs out. Read the iOS SDK documentation for more details on this delegate.
We recommend that users update to the latest Facebook Application whenever possible.
Adding SSO support to your app is easy to do. So let's walk you through this.
Create your iOS Project
Open Xcode and create a new iOS project using the
In order to use the iOS Facebook SDK, the source files from that SDK project must be brought into the app project. This can be done a number of different ways, but the easiest way is to just drag the src folder from the local Git repository for the SDK (e.g. ~/facebook-ios-sdk/src) into the app Xcode project. If you have problems dragging the src folder in then simply include the src directory into your project. Additionally, you may exclude the .pch and .xcodeproj files.
Creating an iOS Facebook SDK Static Library
If you create an iOS app that has Automatic Reference Counting (ARC) enabled then you should use a static library version of the iOS Facebook SDK instead of dragging in the files from the src folder. The latest release of the iOS Facebook SDK includes a shell script you can run to build the static library. You would do this through the command line by calling the build_facebook_ios_sdk_static_lib.sh
scripts
directory, for example:
% ~/facebook-ios-sdk/scripts/build_facebook_ios_sdk_static_lib.sh
This will create the static library under the <PROJECT_HOME>/lib/facebook-ios-sdk folder (e.g. ~/facebook-ios-sdk/lib/facebook-ios-sdk). You may then drag the facebook-ios-sdk folder into the app Xcode project to include the iOS Facebook SDK static library.
Modify the application delegate header file
Step 1. Add an #import
#import "FBConnect.h"
Step 2. Set the application delegate class to handle the Facebook session delegate callback by modifying the header file to add FBSessionDelegate to the list of delegates. For example for the MyGreatIOSApp:
@interface MyGreatIOSAppAppDelegate: NSObject <UIApplicationDelegate, FBSessionDelegate>
Step 3. Set up the application delegate header file by creating instance variable:
Facebook *facebook;
Step 4. Add a property for an instance of the
@property (nonatomic, retain) Facebook *facebook;
Modify the application delegate implementation file
Step 1. Synthesize the facebook
@synthesize facebook;
Step 2. Within the body of the application:didFinishLaunchingWithOp
facebook = [[Facebook alloc] initWithAppId:@"YOUR_APP_ID" andDelegate:self];
This instance is used to invoke SSO, as well as the Graph API and Platform Dialogs from within the app.
Step 3. Once the instance is created, check for previously saved access token information. (We will show you how to save this information in Step 6.) Use the saved information to set up for a session valid check by assigning the saved information to the facebook
access_token
. If you have asked for offline_access
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; if ([defaults objectForKey:@"FBAccessTokenKey"] && [defaults objectForKey:@"FBExpirationDateKey"]) { facebook.accessToken = [defaults objectForKey:@"FBAccessTokenKey"]; facebook.expirationDate = [defaults objectForKey:@"FBExpirationDateKey"]; }
Step 4. Check for a valid session and if it is not valid call the authorize
if (![facebook isSessionValid]) { [facebook authorize:nil]; }
Step 5. Add the application:handleOpenURL:
application:openURL:
facebook
// Pre iOS 4.2 support - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url { return [facebook handleOpenURL:url]; } // For iOS 4.2+ support - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation { return [facebook handleOpenURL:url]; }
The relevant method is called by iOS when the Facebook App redirects to the app during the SSO process. The call to Facebook::handleOpenURL:
Step 6. Implement the fbDidLogin
FBSessionDelegate
NSUserDefaults
:
- (void)fbDidLogin { NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; [defaults setObject:[facebook accessToken] forKey:@"FBAccessTokenKey"]; [defaults setObject:[facebook expirationDate] forKey:@"FBExpirationDateKey"]; [defaults synchronize]; }
Modify the app property list file
The last thing that needs to be accomplished to enable SSO support is a change to the .plist
That is it. SSO is ready to go. All that remains is to build and debug the app to ensure anything is setup up correctly.
Test your app
You can test SSO using either your simulator or a device. If you use a simulator you should make sure you log in to Facebook on the mobile browser. To test on the device make sure you are currently logged in to the Facebook app. Initially you can test on a simulator.
Build and run your app from Xcode. When the app starts in the emulator, you should see the following dialog:
This screen is known as the user authorization dialog. It allows the user to grant your app permission to access their information. If the user presses facebook
Step 4: Adding Log Out to your App
When the user wants to stop using Facebook integration with your app, you can call the logout
access_token
.
[facebook logout];
You may implement the fbDidLogout
FBSessionDelegate
Note that logging out will not revoke your application's permissions, but will simply clear your application'saccess_token
. If a user that has previously logged out of your app returns, they will simply see a notification that they are logging into your app, not a notification to grant permissions. To modify or revoke an application's permissions, the user can visit the
Now add a logout button and handler to your sample app.
Step 1. Add the logout button and handler:
Modify MyGreatIOSAppAppDelegateapplication:didFinishLaunchingWithOp
// Add the logout button
UIButton *logoutButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
logoutButton.frame = CGRectMake(40, 40, 200, 40);
[logoutButton setTitle:@"Log Out" forState:UIControlStateNormal];
[logoutButton addTarget:self action:@selector(logoutButtonClicked)
forControlEvents:UIControlEventTouchUpIns ide];
[self.viewController.view addSubview:logoutButton];
Now add logic to call the logout
// Method that gets called when the logout button is pressed
- (void) logoutButtonClicked:(id)sender {
[facebook logout];
}
Step 2. Add the logout callback handler:
Modify MyGreatIOSAppAppDelegateFBSessionDelegate
- (void) fbDidLogout {
// Remove saved authorization information if it exists
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:@"FBAccessTokenKey"]) {
[defaults removeObjectForKey:@"FBAccessTokenKey"];
[defaults removeObjectForKey:@"FBExpirationDateKey"];
[defaults synchronize];
}
}
Save, build, and run your application. Tap on the logout button. In this simple example we have not implemented a visual cue that log out was successful. However, if you relaunch your app you should be asked to authorize it once again.
Step 5: Requesting Additional Permissions
By default, the user is asked to authorize the app to access basic information that is available publicly or by default on Facebook. If your app needs more than this basic information to function, you must request specific permissions from the user. This is accomplished by passing a NSArray
authorize
NSArray *permissions = [[NSArray alloc] initWithObjects: @"user_likes", @"read_stream", nil]; [facebook authorize:permissions]; [permissions release];
Permissions related to the user and friends will be shown in the first authorization screen. In our example this is the user_likes
read_stream
A full list of permissions is available in our
Let's go ahead and test this out. Modify the tutorial's app delegate implementation file to see this in action. In theauthorize
if (![facebook isSessionValid]) { NSArray *permissions = [[NSArray alloc] initWithObjects: @"user_likes", @"read_stream", nil]; [facebook authorize:permissions]; [permissions release]; }
Save, build, and run your application. Verify that you get the authorization dialogs for the permissions you have requested.
Adding Social Context
Step 6: Using the Graph API
The Facebook
You can access the Graph API by passing the Graph Path to the request method. For example, to access information about the logged in user, call:
// get information about the currently logged in user
[facebook requestWithGraphPath:@"me" andDelegate:self];
// get the posts made by the "platform" page
[facebook requestWithGraphPath:@"platform/posts" andDelegate:self];
// get the logged-in user's friends
[facebook requestWithGraphPath:@"me/friends" andDelegate:self];
Your delegate object should implement the FBRequestDelegate
Note that the server response will be in JSON string format. The SDK uses an open source JSON libraryhttps://github.com/stig/json-framework/ request:didFailWithError:
A successful request will callback request:didLoad:
NSArray
, if there are multiple results, or an NSDictionary
Advanced apps may want to provide their own custom parsing and/or error handling, depending on their individual needs.
Read the FBRequestDelegate
Step 7: Integrating with Social Channels
Social Channels enable users to post to their friends' News Feed or send a Request to their friends. The iOS SDK provides a method for integrating social channels through
-
Feed Dialog
- the dialog used for publishing posts to a user's News Feed. -
Requests Dialog
- the dialog used to send a request to one or more friends.
This allows you to provide basic Facebook functionality in your app with a few lines of code -- no need to build native dialogs, make API calls, or handle responses. Refer to the
Requests
Requests are a great way to enable users to invite their friends to your mobile web app or to take specific action like accepting a gift. Your mobile web app can send requests by using the
An example requests dialog that allows you to send requests to any of your friends:
NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAnd Keys:
@"Come check out my app.", @"message",
nil];
[facebook dialog:@"apprequests"
andParams:params
andDelegate:self];
News Feed
The News Feed is shown immediately to users upon logging in to Facebook, making it core to the Facebook experience. Your mobile web app can post to the user's news feed by using the
To invoke the feed dialog:
[facebook dialog:@"feed" andDelegate:self];
Timeline and Open Graph
Historically, Facebook has managed this graph and has expanded it over time as we launch new products (photos, places, etc.). In 2010, we extended the social graph, via the Open Graph protocol, to include 3rd party web sites and pages that people liked throughout the web. We are now extending the Open Graph to include arbitrary actions and objects created by 3rd party apps and enabling these apps to integrate deeply into the Facebook experience.
After a user adds your app to their Timeline, app specific actions are shared on Facebook via the Open Graph. As your app becomes an important part of how users express themselves, these actions are more prominently displayed throughout the Facebook Timeline and News Feed. This enables your app to become a key part of the user's and their friend's experience on Facebook.
Timeline is coming to mobile soon. In preparation, you can start integrating now.
To learn more about how you can integrate your app into Open Graph and Timeline,
Advanced Configuration
Step 8: Sharing an App ID across Multiple Apps
You can use one app ID across multiple apps. One scenario where you may want to do this is if you have a free and paid version of your iOS app. Facebook allows you to define a URL Scheme Suffix parameter, urlSchemeSuffix
, that you pass on to the app initWithAppId:urlSchemeSuffix:andDelegate:
urlSchemeSuffix
.plist
Note:
To show you how to do this let's modify the previous. We will define a URL Scheme Suffix named ''foo''.
Step 1. When calling the initWithAppId:urlSchemeSuffix:andDelegate:
facebook = [[Facebook alloc] initWithAppId:@"YOUR_APP_ID" urlSchemeSuffix:@"foo" andDelegate:self];
Step 2. Modify the unique URL in the .plist
Modify the URL Schemes entry from
That is all you have to do to support SSO from multiple iOS apps with the same Facebook app ID. Build and run the app to ensure that your app works as before with the new SSO URL.
When you have properly set up and configured SSO you can get
The order in which you list the suffixes determines the order that the Facebook app will search for the installed app when linking to your app. For example, if you list two URL Scheme Suffix entries, ''freeapp'' (for your free app) and ''paidapp'' (for your paid app), then the Facebook app will first look for the free app then the paid app. If you want the Facebook app to look for the paid app first, then put the corresponding suffix first in the list.
Step 9: Setting up for Facebook iOS App Distribution and Deep Linking
If your app is SSO-enabled then you can get distribution through the Facebook iOS app. The following diagram shows how this distribution flows from when a user first interacts with a 3rd party app, publishes a news story or sends an app request, to how these stories and request notifications drive back to your app. The diagram also shows how app search and bookmarks can drive distribution from the Facebook app.
When a user taps on an app notification or clicks on a story that links to the 3rd party app will be provided with the original URL. This can be used to deep link into the 3rd party app. The notification URL or News Feed URL is sent to the app in the target_url
application:handleOpenURL:
application:openURL:sourceApplication:annotation:
If the user has your application installed, and has authenticated your app with Facebook, here is the URL we open:
fb[app id]://authorize#expires_in=0&access_token=[token]&target_url=[Linked URL]
If the app is installed, but the user has not authenticated it with Facebook, the URL format is:
fb[app id]://authorize#target_url=[Linked URL]
To summarize, these are the channels that can drive distribution back to your app:
- App search: your app will be visible if it passes an active usage threshold.
- App bookmarks: your app will be visible to users who have previously used it and based on a usage threshold.
- App request notifications: requests 2.0 notifications sent to a friend will link back to your app.
- Story attribution: your app source attribution will be visible if you set up your app with a namespace.
- Story links: you can configure links in your News Feed stories that will point back to your app.
Let's walk through a tutorial of setting up and verifying Facebook app distribution.
Step 1. Configure your app settings in the
Make the following changes to your app's basic settings:
App Namespace
- Set a unique namespace for your app. This namespace can be used for configuring story links back to your site. iPhone App Store ID
- If you have an iPhone app that is listed in the iTunes App Store enter the ID here, e.g. 123456. If Facebook links out to your app and finds that the user does not have your app installed, then it will take the user to your app in the store. The user can then install your app. If your app is not in the iTunes App Store you can enter any valid app's ID but be sure to update this when your app is approved in the App Store. iPad App Store ID
- If you have a separate iPad app that is listed in the iTunes App Store enter the ID here, e.g. 123456. If Facebook links out to your app and finds that the user does not have your app installed, then it will take the user to your app in the store. The user can then install your app. If your app is not in the iTunes App Store you can enter any valid app's ID but be sure to update this when your app is approved in the App Store. Configured for iOS SSO
- you must enable this setting if you want your app to be visible in bookmarks and through search results. Make sure that you turn this on after you have properly implemented SSO. iOS native deep linking
- you must enable this setting if you want your app to be linked to from News Stories. You must also enable the Configured for iOS SSO
setting to turn on this feature. If you wish to handle your own News Story links then disable this setting. URL Scheme Suffix
- you should enter this information if you have multiple apps sharing the same Facebook app ID. The entries here should contain the URL Scheme Suffix set up for each of your iOS apps. To handle the case where the user may have installed multiple versions of your app, you want to order the entries based on the order in which you want the Facebook app to search for the apps. iOS Bundle ID
- (Optional) You may set this to match the bundle ID for your iOS app. If you add this setting then the bundle ID of your app will be checked before authorizing the user. The benefit of this setting for SSO is if the user has already authorized your app they will not be asked to authorize it when they access your app from a new device.
When Facebook iOS app launches your app it will check if the user has already authorized your app. If the user is authorized then an access_token
access_token
Step 2. Check the app search flow:
When a user does a search in the Facebook app your app will be visible if it passes a usage threshold. The search results will display apps that have been configured for SSO support. When the user selects your app from the search results they will be directed to your app. If the user had previously authorized your app they will be authenticated when your app is launched.
Test out app search results results by launching the Facebook iOS app. Search for the name of your app as specified in the Facebook Dev App settings. If your app shows up in the results tap on the link and make sure that your app is launched. Verify that you are authenticated (access_token
Step 3. Check the app bookmarks flow:
A user who has previously installed your app may see it listed under the App section in the main menu for the app if the app has been actively used. When the user selects your app they will be directed to your app. If the user had previously authorized your app they will be authenticated when your app is launched.
Use the app actively for a while first. Test out app bookmarks by launching the Facebook iOS app and check that your app is listed in the App section.. Tap on your app and make sure that it is launched. Verify that you are authenticated (access_token
Step 4. Exercise the app request notification flow:
You can send app requests to friends that will show up as notifications. Tapping the notification will launch your app.
-
Modify MyGreatIOSAppAppDelegate
.h file from the previous tutorial and add FBDialogDelegate
to the list of supported protocols: @interface MyGreatIOSAppAppDelegate
: NSObject <UIApplicationDelegate, FBSessionDelegate, FBDialogDelegate> { Facebook *facebook; } -
Modify MyGreatIOSAppAppDelegate
.m file from the previous tutorial and add the following code to the beginning of the application:didFinishLaunchingWithOp
tions: method: // Add the requests dialog button UIButton *requestDialogButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; requestDialogButton.frame = CGRectMake(40, 150, 200, 40); [requestDialogButton setTitle:@"Send Request" forState:UIControlStateNormal]; [requestDialogButton addTarget:self action:@selector(requestDialogButtonClick
ed) forControlEvents:UIControlEventTouchUpIns ide]; [self.viewController.view addSubview:requestDialogButton]; -
Modify MyGreatIOSAppAppDelegate
.m file from the previous tutorial and add the following new method: // Method that gets called when the request dialog button is pressed - (void) requestDialogButtonClick
ed { NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAnd Keys: @"invites you to check out cool stuff", @"message", @"Check this out", @"notification_text", nil]; [facebook dialog:@"apprequests" andParams:params andDelegate:self]; } // FBDialogDelegate - (void)dialogDidComplete:(FBDialog *)dialog { NSLog(@"dialog completed successfully"); } -
Build and run your sample app.
- Send an app request to a friend who has your app installed and has authorized the app.
- Have your friend launch Facebook iOS app and check that they have received your notification.
- They should click on the notification and verify that your app launches.
Step 5. Exercise the app story link flow:
When you have enabled iOS native deep linking
-
Modify MyGreatIOSAppAppDelegate
.m file from the previous tutorial and add the following code to the beginning of the application:didFinishLaunchingWithOp
tions: method: // Add the feed dialog button UIButton *feedDialogButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; feedDialogButton.frame = CGRectMake(40, 260, 200, 40); [feedDialogButton setTitle:@"Publish Feed" forState:UIControlStateNormal]; [feedDialogButton addTarget:self action:@selector(feedDialogButtonClicked) forControlEvents:UIControlEventTouchUpIns
ide]; [self.viewController.view addSubview:feedDialogButton]; -
Modify MyGreatIOSAppAppDelegate
.m file from the previous tutorial and add the following new method: // Method that gets called when the feed dialog button is pressed - (void) feedDialogButtonClicked { NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAnd
Keys: @"Testing Feed Dialog", @"name", @"Feed Dialogs are Awesome.", @"caption", @"Check out how to use Facebook Dialogs.", @"description", @"http://www.example.com/", @"link", @"http://fbrell.com/f8.jpg", @"picture", nil]; [facebook dialog:@"feed" andParams:params andDelegate:self]; } -
In your code, replace
www.example.com with a link to your website. - Build and run your sample app.
- Publish a feed story.
- Open up Facebook iOS app and check the feed story.
- Click on the story link and verify that your app launches.
Step 6. Exercise the app story attribution flow:
When you publish a News Story there will be an app attribution linked to it. If you have configured SSO support then if a user clicks on the "via YOUR_APP" link they will be directed to your app.
If you completed the previous New Feed publishing step, do the following:
- Publish a feed story.
- Open up Facebook iOS app and check the feed story.
- Click on the story attribution link and verify that your app is opened up.
Those are all the steps you need to take to set up and verify distribution through Facebook iOS app.
Additional Topics
Handle Errors
Errors are handled by the FBRequestDelegate
FBDialogDelegate
Read more about error handling in the
Extending the Access Token
Step 1. Implement FBSessionDelegate delegate method fdDidExtendToken and save the new token and expiration time. Here is an example:
-(void)fbDidExtendToken:(NSString *)accessToken expiresAt:(NSDate *)expiresAt { NSLog(@"token extended"); NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; [defaults setObject:accessToken forKey:@"FBAccessTokenKey"]; [defaults setObject:expiresAt forKey:@"FBExpirationDateKey"]; [defaults synchronize]; }
Step 2. Call [facebook extendAccessTokenIfNeede
- (void)applicationDidBecomeActive:(UIApplication *)application { [facebook extendAccessTokenIfNeede d]; }
Note: Make sure you have the latest iOS SDK that includes support for extending access tokens.
Sample Apps
The Github repository contains a sample applications that showcase Facebook Platform integration:
-
Hackbook for iOS: includes SSO and sample API calls. This sample is targeted towards iOS developers who want to build social apps.
-
Wishlist: Open Graph sample to demonstrate the use of custom objects and actions in a mobile application.