本文共 33300 字,大约阅读时间需要 111 分钟。
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:
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!
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
Install
Clone the 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.
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
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
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.
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.
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
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;
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];}
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.
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
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 buttonUIButton *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 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.
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.
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 library 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
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
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 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 dictionaryWithObjectsAndKeys: @"Come check out my app.", @"message", nil]; [facebook dialog:@"apprequests" andParams:params andDelegate:self];
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];
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,
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.
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:
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
iPhone App Store ID
iPad App Store ID
Configured for iOS SSO
iOS native deep linking
Configured for iOS SSO
URL Scheme Suffix
iOS Bundle ID
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 MyGreatIOSAppAppDelegateFBDialogDelegate
@interface MyGreatIOSAppAppDelegate : NSObject{ Facebook *facebook; }
Modify MyGreatIOSAppAppDelegateapplication:didFinishLaunchingWithOp
// Add the requests dialog buttonUIButton *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
// 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.
Step 5. Exercise the app story link flow:
When you have enabled iOS native deep linking
Modify MyGreatIOSAppAppDelegateapplication:didFinishLaunchingWithOp
// Add the feed dialog buttonUIButton *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
// 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", @"http://www.example.com/", @"link", @"http://fbrell.com/f8.jpg", @"picture", nil]; [facebook dialog:@"feed" andParams:params andDelegate:self];}
In your code, replace
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:
Those are all the steps you need to take to set up and verify distribution through Facebook iOS app.
Errors are handled by the FBRequestDelegate
FBDialogDelegate
Read more about error handling in the
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 extendAccessTokenIfNeeded];}
Note: Make sure you have the latest iOS SDK that includes support for extending access tokens.
The Github repository contains a sample applications that showcase Facebook Platform integration:
: includes SSO and sample API calls. This sample is targeted towards iOS developers who want to build social apps.
: Open Graph sample to demonstrate the use of custom objects and actions in a mobile application.
转载地址:http://jjeji.baihongyu.com/