Professional Documents
Culture Documents
1/15/12 11:35 AM
Documentation
Support
Blog
Apps
Getting Started Websites Apps on Facebook Mobile Samples & How-Tos Videos Core Concepts Advanced Topics SDKs & Tools Open Graph Beta
iOS Tutorial
Getting Started Mobile iOS Tutorial
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: 1. 2. 3. 4. 5. Registering your iOS App with Facebook Installing the iOS SDK Implementing Single Sign-On Adding Log Out to your App Requesting Additional Permissions
Adding Social Context: 6. Using the Graph API 7. Integrating with Social Channels Advanced Configuration: 8. Sharing an App ID across Multiple Apps 9. Setting up for Facebook iOS App Distribution Additional Topics: Handle Errors Sample Apps
Note your App ID. You are going to need it when setting up your app in Xcode. You application is now set up and youre ready to begin integrating with Facebook!
https://developers.facebook.com/docs/mobile/ios/build/
Page 1 of 16
1/15/12 11:35 AM
#import "FBConnect.h"
Step 2. Set the application delegate class to handle the Facebook session delegate callback by modifying the header file to
https://developers.facebook.com/docs/mobile/ios/build/
Page 2 of 16
1/15/12 11:35 AM
add FBSessionDelegate to the list of delegates. For example for the MyGreatIOSApp:
Facebook *facebook;
Step 4. Add a property for an instance of the Facebook class:
@synthesize facebook;
Step 2. Within the body of the application:didFinishLaunchingWithOptions: method create instance of the Facebook class using your app ID (available from the Developer App):
https://developers.facebook.com/docs/mobile/ios/build/
Page 3 of 16
1/15/12 11:35 AM
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 method which will both log the user in and prompt the user to authorize the app:
// Pre 4.2 support - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url { return [facebook handleOpenURL:url]; } // For 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: provides the app with the user's credentials. Step 6. Implement the fbDidLogin method from the FBSessionDelegate implementation. In this method you will save the user's credentials specifically the access token and corresponding expiration date. For simplicity you will save this in the user's preferences - NSUserDefaults:
- (void)fbDidLogin { NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; [defaults setObject:[facebook accessToken] forKey:@"FBAccessTokenKey"]; [defaults setObject:[facebook expirationDate] forKey:@"FBExpirationDateKey"]; [defaults synchronize]; }
https://developers.facebook.com/docs/mobile/ios/build/
Page 4 of 16
1/15/12 11:35 AM
https://developers.facebook.com/docs/mobile/ios/build/
Page 5 of 16
1/15/12 11:35 AM
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.
This screen is known as the user authorization dialog. It allows the user to grant your app permission to access their
https://developers.facebook.com/docs/mobile/ios/build/
Page 6 of 16
1/15/12 11:35 AM
information. If the user presses Allow, your app is authorized and you will have access to the user's profile and social graph through the facebook instance. If the user presses Don't Allow, your app is not authorized and you will not have access to the user's data.
[facebook logout];
You may implement the fbDidLogout method of the FBSessionDelegate protocol to handle any post-logout actions you wish to take. Note that logging out will not revoke your application's permissions, but will simply clear your application's access_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 "Applications, Games, and Websites" tab of their Facebook privacy settings dashboard. You can also revoke an app's permissions programmatically using a Graph API call. Now add a logout button and handler to your sample app. Step 1. Add the logout button and handler: Modify MyGreatIOSAppAppDelegate.m file from the tutorial and add the following code to the beginning of the application:didFinishLaunchingWithOptions: method:
// 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:UIControlEventTouchUpInside]; [self.viewController.view addSubview:logoutButton];
Now add logic to call the logout method when the button is tapped. Modify MyGreatIOSAppAppDelegate.m file from the previous tutorial and add the following new method:
// Method that gets called when the logout button is pressed - (void) logoutButtonClicked:(id)sender { [facebook logout]; }
Step 2. Add the logout callback handler: Modify MyGreatIOSAppAppDelegate.m file from the previous tutorial and add the FBSessionDelegate callback method for a successful logout:
- (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.
1/15/12 11:35 AM
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 of permissions to the authorize method. The following example shows how to ask for access to pages a user has liked and to their News Feed:
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 permission. Extended permissions will be requested in the second authorization screen. In our example this is the read_stream permissions. You can refer to the permissions guide for more information.
https://developers.facebook.com/docs/mobile/ios/build/
Page 8 of 16
1/15/12 11:35 AM
A full list of permissions is available in our permissions reference. There is a strong inverse correlation between the number of permissions your app requests and the number of users that will allow those permissions. The greater the number of permissions you ask for, the lower the number of users that will grant them; so we recommend that you only request the permissions you absolutely need for your app. Let's go ahead and test this out. Modify the tutorial's app delegate implementation file to see this in action. In the authorize method, pass in a permissions array:
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.
// 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 interface to handle your request responses. Note that the server response will be in JSON string format. The SDK uses an open source JSON library https://github.com/stig/json-framework/ to parse the result. If a parsing error occurs, the SDK will callback request:didFailWithError: in your delegate. A successful request will callback request:didLoad: in your delegate. The result passed to your delegate can be an NSArray, if there are multiple results, or an NSDictionary if there is only a single result. Advanced apps may want to provide their own custom parsing and/or error handling, depending on their individual needs. Read the iOS SDK documentation for more details on the FBRequestDelegate delegate.
https://developers.facebook.com/docs/mobile/ios/build/
Page 9 of 16
1/15/12 11:35 AM
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 mobile distribution guide for details on supported Social Channels.
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 Request dialog. If the users device supports it, they will receive a Push Notification via the Facebook native app whenever a friend sends them a request, in addition to the notification they normally get within Facebook. An example requests dialog that allows you to send requests to any of your friends:
NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys: @"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 Feed Dialog. To invoke the feed dialog:
https://developers.facebook.com/docs/mobile/ios/build/
Page 10 of 16
1/15/12 11:35 AM
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 Facebook distribution to your app. If you have multiple apps using a single Facebook app ID you will need to add a configuration to the Dev App to list the URL Scheme Suffix information for the apps that share one ID.
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.
https://developers.facebook.com/docs/mobile/ios/build/
Page 11 of 16
1/15/12 11:35 AM
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 parameter of the callback link. You can modify the application:handleOpenURL: or application:openURL:sourceApplication:annotation: methods in the app delegate implementation file to customize how your app will handle these notifications. 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 Developer App:
https://developers.facebook.com/docs/mobile/ios/build/
Page 12 of 16
1/15/12 11:35 AM
Make the following changes to your app's basic settings: 1. App Namespace - Set a unique namespace for your app. This namespace can be used for configuring story links back to your site. 2. 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. 3. 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. 4. Configured for iOS SSO - you must enable this setting if you want your app to be visible in bookmarks, through search results, or linked to from News Stories. Make sure that you turn this on after you have properly implemented SSO. 5. 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. 6. 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 will be passed to your app which means that the user will be authenticated when your app is launched. If the user has not authorized your app then no access_token will be passed to your app and the user will not be authenticated when your app is launched. 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.
https://developers.facebook.com/docs/mobile/ios/build/
Page 13 of 16
1/15/12 11:35 AM
Verify that you are authenticated (access_token valid) if you had previously authorized the app. 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 valid) if you had previously authorized the app. 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:
// 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(requestDialogButtonClicked) forControlEvents:UIControlEventTouchUpInside]; [self.viewController.view addSubview:requestDialogButton];
Modify MyGreatIOSAppAppDelegate.m file from the previous tutorial and add the following new method:
https://developers.facebook.com/docs/mobile/ios/build/
Page 14 of 16
1/15/12 11:35 AM
// Method that gets called when the request dialog button is pressed - (void) requestDialogButtonClicked { NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys: @"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: You can publish stories with links that you configure to open your app when clicked. Your links should be of the form m.facebook.com/apps/[YOUR_APP_NAMESPACE]. Facebook will apply re-writing rule to help redirect these types of links back to your app. Modify MyGreatIOSAppAppDelegate.m file from the previous tutorial and add the following code to the beginning of the application:didFinishLaunchingWithOptions: 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:UIControlEventTouchUpInside]; [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 dictionaryWithObjectsAndKeys: @"Testing Feed Dialog", @"name", @"Feed Dialogs are Awesome.", @"caption", @"Check out how to use Facebook Dialogs.", @"description", @"https://m.facebook.com/apps/YOUR_APP_NAMESPACE/", @"link", @"http://fbrell.com/f8.jpg", @"picture", nil]; [facebook dialog:@"feed" andParams:params andDelegate:self]; }
In your code, replace YOUR_APP_NAMESPACE with the app namespace you defined in the Dev App. 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:
https://developers.facebook.com/docs/mobile/ios/build/
Page 15 of 16
1/15/12 11:35 AM
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.
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.
Report Documentation Bug Updated about a month ago
About
Platform Policies
Privacy Policy
https://developers.facebook.com/docs/mobile/ios/build/
Page 16 of 16