Facebook Share iOS Tutorial
来源:互联网 发布:手机淘宝5.9.9官方版 编辑:程序博客网 时间:2024/05/30 04:59
iOS Tutorial
(http://developers.facebook.com/docs/mobile/ios/build/#register)
This document will guide you through Facebook Platform integrationfor iOS. We will walk you through a tutorial to show the key stepsto building a social iOS app. This will include showing you how toenable Single Sign-On. We will also cover additional topics aroundintegrating with Facebook Platform.
Getting Started:
Adding SocialContext:
AdvancedConfiguration:
Additional Topics:
- HandleErrors
- Extendingthe Access Token
- SampleApps
Getting Started
Step 1: Registering your iOS App with Facebook
To begin integrating with the FacebookPlatform,
Note your App ID. You are going to need it when setting up your appin Xcode.
You application is now set up and you’re ready to begin integratingwith Facebook!
Step 2: Installing the iOS SDK
Before you begin development with the Facebook iOS SDK, you willneed to install the iOS dev tools, Git (the source control clientwe use for this SDK) and then clone the latest version of the SDKfrom
Install
Xcode Install
Git Clone the
GitHubrepository: gitclone git://github.com/facebook/facebook-ios-sdk.git
Once you have everything installed you are now ready to set up youriOS app. First we will discuss Single Sign-On (SSO) which is a keyimplementation feature you should provide. After that section wewill walk you through the steps of setting up an iOS app andenabling SSO.
Step 3: Implementing Single Sign-On (SSO)
One of the most compelling features of the iOS SDKis
SSO primarily works by redirecting the user to the Facebook app onher device. Since the user is already logged into Facebook, theywill not need to enter their username and password to identifythemselves. They will see the auth dialog with the permissions thatyour app has asked for and if they allow then they will beredirected to your app with theappropriate access_token
.
Developers should be aware that Facebook SSO will behave slightlydifferent depending on what is installed on the user's device. Thisis what happens in certain configurations:
If the app is running in a version of iOS that supportsmultitasking, and if the device has the Facebook app of version3.2.3 or greater installed, the SDK attempts to open theauthorization dialog within the Facebook app. After the user grantsor declines the authorization, the Facebook app redirects back tothe calling app, passing the authorization token, expiration, andany other parameters the Facebook OAuth server may return.
If the device is running in a version of iOS that supportsmultitasking, but it doesn't have the Facebook app of version 3.2.3or greater installed, the SDK will open the authorization dialog inSafari. After the user grants or revokes the authorization, Safariredirects back to the calling app. Similar to the Facebook appbased authorization, this allows multiple apps to share the sameFacebook user
access_token
throughthe Safari cookie. If the app is running a version of iOS that does not supportmultitasking, the SDK uses the old mechanism of popping up aninline UIWebView, prompting the user to log in and grant access.The
FBSessionDelegate
isa callback interface that your app should implement: The delegate'smethods will be invoked when the app successful logs in or logsout. Read the iOSSDK documentation for more details on thisdelegate.
We recommend that users update to the latest Facebook Applicationwhenever possible.
Adding SSO support to your app is easy to do. So let's walk youthrough this.
Create your iOS Project
Open Xcode and create a new iOS project usingthe
In order to use the iOS Facebook SDK, the source files from thatSDK project must be brought into the app project. This can be donea number of different ways, but the easiest way is to just drag thesrc folder from the local Git repository for the SDK (e.g.~/facebook-ios-sdk/src) into the app Xcode project. If you haveproblems dragging the src folder in then simply include the srcdirectory into your project. Additionally, you may exclude the .pchand .xcodeproj files.
Creating an iOS Facebook SDKStatic Library
If you create an iOS app that has Automatic Reference Counting(ARC) enabled then you should use a static library version of theiOS Facebook SDK instead of dragging in the files from the srcfolder. The latest release of the iOS Facebook SDK includes a shellscript you can run to build the static library. You would do thisthrough the command line by callingthe 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-sdkfolder (e.g. ~/facebook-ios-sdk/lib/facebook-ios-sdk). You may thendrag the facebook-ios-sdk folder into the app Xcode project toinclude 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 theFacebook session delegate callback by modifying the header file toadd FBSessionDelegate to the list of delegates. For example for theMyGreatIOSApp:
@interface MyGreatIOSAppAppDelegate: NSObject <UIApplicationDelegate, FBSessionDelegate>
Step 3. Set up the application delegate header file bycreating instance variable:
Facebook *facebook;
Step 4. Add a property for an instance ofthe
@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 andPlatform Dialogs from within the app.
Step 3. Once the instance is created, check for previouslysaved access token information. (We will show you how to save thisinformation in Step 6.) Use the saved information to set up for asession valid check by assigning the saved information tothe 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 validcall 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 Appredirects to the app during the SSO process. The callto 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 supportis a change to the .plist
That is it. SSO is ready to go. All that remains is to build anddebug the app to ensure anything is setup up correctly.
Test your app
You can test SSO using either your simulator or a device. If youuse a simulator you should make sure you log in to Facebook on themobile browser. To test on the device make sure you are currentlylogged in to the Facebook app. Initially you can test on asimulator.
Build and run your app from Xcode. When the app starts in theemulator, you should see the following dialog:
This screen is known as the user authorization dialog. It allowsthe 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 yourapp, you can call the logout
access_token
.
[facebook logout];
You may implement the fbDidLogout
FBSessionDelegate
Note that logging out will not revoke your application'spermissions, but will simply clear your application'saccess_token
.If a user that has previously logged out of your app returns, theywill simply see a notification that they are logging into your app,not a notification to grant permissions. To modify or revoke anapplication's permissions, the user can visitthe
Now add a logout button and handler to your sample app.
Step 1. Add the logoutbutton 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 logoutcallback 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. Inthis simple example we have not implemented a visual cue that logout was successful. However, if you relaunch your app you should beasked to authorize it once again.
Step 5: Requesting Additional Permissions
By default, the user is asked to authorize the app to access basicinformation that is available publicly or by default on Facebook.If your app needs more than this basic information to function, youmust request specific permissions from the user. This isaccomplished 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 thefirst authorization screen. In our example this isthe user_likes
read_stream
A full list of permissions is available inour
Let's go ahead and test this out. Modify the tutorial's appdelegate implementation file to see this in action. Intheauthorize
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 theauthorization 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 therequest method. For example, to access information about the loggedin 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 implementthe FBRequestDelegate
Note that the server response will be in JSON string format. TheSDK 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/orerror 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 orsend a Request to their friends. The iOS SDK provides a method forintegrating social channels through
Feed Dialog
- the dialog used for publishingposts to a user's News Feed. RequestsDialog
- the dialog used to send a request toone or more friends.
This allows you to provide basic Facebook functionality in your appwith a few lines of code -- no need to build native dialogs, makeAPI calls, or handle responses. Refer tothe
Requests
Requests are a great way to enable users to invite their friends toyour mobile web app or to take specific action like accepting agift. Your mobile web app can send requests by usingthe
An example requests dialog that allows you to send requests to anyof 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 toFacebook, making it core to the Facebook experience. Your mobileweb app can post to the user's news feed by usingthe
To invoke the feed dialog:
[facebook dialog:@"feed" andDelegate:self];
Timeline and Open Graph
Historically, Facebook has managed this graph and has expanded itover time as we launch new products (photos, places, etc.). In2010, we extended the social graph, via the Open Graph protocol, toinclude 3rd party web sites and pages that people liked throughoutthe web. We are now extending the Open Graph to include arbitraryactions and objects created by 3rd party apps and enabling theseapps to integrate deeply into the Facebook experience.
After a user adds your app to their Timeline, app specific actionsare shared on Facebook via the Open Graph. As your app becomes animportant part of how users express themselves, these actions aremore prominently displayed throughout the Facebook Timeline andNews Feed. This enables your app to become a key part of the user'sand their friend's experience on Facebook.
Timeline is coming to mobile soon. In preparation, you can startintegrating now.
To learn more about how you can integrate your app into Open Graphand Timeline,
Advanced Configuration
Step 8: Sharing an App ID across Multiple Apps
You can use one app ID across multiple apps. One scenario where youmay want to do this is if you have a free and paid version of youriOS app. Facebook allows you to define a URL Scheme Suffixparameter, 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 willdefine a URL Scheme Suffix named ''foo''.
Step 1. When callingthe initWithAppId:urlSchemeSuffix:andDelegate:
facebook = [[Facebook alloc] initWithAppId:@"YOUR_APP_ID" urlSchemeSuffix:@"foo" andDelegate:self];
Step 2. Modify theunique URL in the .plist
Modify the URL Schemes entry from
That is all you have to do to support SSO from multiple iOS appswith the same Facebook app ID. Build and run the app to ensure thatyour app works as before with the new SSO URL.
When you have properly set up and configured SSO you canget
The order in which you list the suffixes determines the order thatthe Facebook app will search for the installed app when linking toyour app. For example, if you list two URL Scheme Suffix entries,''freeapp'' (for your free app) and ''paidapp'' (for your paidapp), then the Facebook app will first look for the free app thenthe paid app. If you want the Facebook app to look for the paid appfirst, then put the corresponding suffix first in the list.
Step 9: Setting up for Facebook iOS App Distribution and DeepLinking
If your app is SSO-enabled then you can get distribution throughthe Facebook iOS app. The following diagram shows how thisdistribution flows from when a user first interacts with a 3rdparty app, publishes a news story or sends an app request, to howthese stories and request notifications drive back to your app. Thediagram also shows how app search and bookmarks can drivedistribution from the Facebook app.
When a user taps on an app notification or clicks on a story thatlinks to the 3rd party app will be provided with the original URL.This can be used to deep link into the 3rd party app. Thenotification URL or News Feed URL is sent to the app inthe target_url
application:handleOpenURL:
application:openURL:sourceApplication:annotation:
If the user has your application installed, and has authenticatedyour 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 withFacebook, the URL format is:
fb[app id]://authorize#target_url=[Linked URL]
To summarize, these are the channels that can drive distributionback to your app:
- Appsearch: your app will be visible if it passes an active usagethreshold.
- Appbookmarks: your app will be visible to users who havepreviously used it and based on a usage threshold.
- Apprequest notifications: requests 2.0 notifications sent to afriend will link back to your app.
- Storyattribution: your app source attribution will be visible if youset up your app with a namespace.
- Storylinks: you can configure links in your News Feed stories thatwill point back to your app.
Let's walk through a tutorial of setting up and verifying Facebookapp distribution.
Step 1. Configure yourapp settings in the
Make the following changes to your app's basic settings:
AppNamespace
- Set a unique namespace for yourapp. This namespace can be used for configuring story links back toyour site. iPhoneApp Store ID
- If you have an iPhone appthat 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 userdoes not have your app installed, then it will take the user toyour app in the store. The user can then install your app. If yourapp is not in the iTunes App Store you can enter any valid app's IDbut be sure to update this when your app is approved in the AppStore. iPadApp Store ID
- If you have a separate iPadapp 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 userdoes not have your app installed, then it will take the user toyour app in the store. The user can then install your app. If yourapp is not in the iTunes App Store you can enter any valid app's IDbut be sure to update this when your app is approved in the AppStore. Configuredfor iOS SSO
- you must enable this settingif you want your app to be visible in bookmarks and through searchresults. Make sure that you turn this on after you haveproperly implementedSSO. iOSnative deep linking
- you must enable thissetting if you want your app to be linked to from News Stories. Youmust also enable the Configuredfor iOS SSO
setting to turn on thisfeature. If you wish to handle your own News Story links thendisable this setting. URLScheme Suffix
- you should enter thisinformation if you have multipleapps sharing the same Facebook app ID. Theentries here should contain the URL Scheme Suffix set up for eachof your iOS apps. To handle the case where the user may haveinstalled multiple versions of your app, you want to order theentries based on the order in which you want the Facebook app tosearch for the apps. iOSBundle ID
- (Optional) You mayset this to match the bundle ID for your iOS app. If you add thissetting then the bundle ID of your app will be checked beforeauthorizing the user. The benefit of this setting for SSO is if theuser has already authorized your app they will not be asked toauthorize it when they access your app from a new device.
When Facebook iOS app launches your app it will check if the userhas already authorized your app. If the user is authorized thenan access_token
access_token
Step2. Check the app search flow:
When a user does a search in the Facebook app your app will bevisible if it passes a usage threshold. The search results willdisplay apps that have been configured for SSO support. When theuser selects your app from the search results they will be directedto your app. If the user had previously authorized your app theywill be authenticated when your app is launched.
Test out app search results results by launching the Facebook iOSapp. Search for the name of your app as specified in the FacebookDev App settings. If your app shows up in the results tap on thelink and make sure that your app is launched. Verify that you areauthenticated (access_token
Step3. Check the app bookmarks flow:
A user who has previously installed your app may see it listedunder the App section in the main menu for the app if the app hasbeen actively used. When the user selects your app they will bedirected to your app. If the user had previously authorized yourapp they will be authenticated when your app is launched.
Use the app actively for a while first. Test out app bookmarks bylaunching the Facebook iOS app and check that your app is listed inthe App section.. Tap on your app and make sure that it islaunched. Verify that you are authenticated (access_token
Step4. Exercise the app request notification flow:
You can send app requests to friends that will show up asnotifications. Tapping the notification will launch your app.
Modify MyGreatIOSAppAppDelegate
.h file from the previous tutorialand add FBDialogDelegate
tothe list of supported protocols: @interface MyGreatIOSAppAppDelegate
: NSObject <UIApplicationDelegate, FBSessionDelegate, FBDialogDelegate> { Facebook *facebook; } Modify MyGreatIOSAppAppDelegate
.m file from the previous tutorialand add the following code to the beginning ofthe application:didFinishLaunchingWithOp
tions: method: // 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(requestDialogButtonClick
ed) forControlEvents:UIControlEventTouchUpIns ide];[self.viewController.view addSubview:requestDialogButton]; Modify MyGreatIOSAppAppDelegate
.m file from the previous tutorialand 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 requestto a friend who has your app installed and has authorized theapp.
- Have your friendlaunch Facebook iOS app and check that they have received yournotification.
- They should clickon the notification and verify that your app launches.
Step5. Exercise the app story link flow:
When you have enabled iOSnative deep linking
Modify MyGreatIOSAppAppDelegate
.m file from the previous tutorialand add the following code to the beginning ofthe application:didFinishLaunchingWithOp
tions: method: // 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:UIControlEventTouchUpIns
ide]; [self.viewController.view addSubview:feedDialogButton]; Modify MyGreatIOSAppAppDelegate
.m file from the previous tutorialand 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 witha link to your website. - Build and run yoursample app.
- Publish a feedstory.
- Open up FacebookiOS app and check the feed story.
- Click on the storylink and verify that your app launches.
Step6. Exercise the app story attribution flow:
When you publish a News Story there will be an app attributionlinked to it. If you have configured SSO support then if a userclicks on the "via YOUR_APP" link they will be directed to yourapp.
If you completed the previous New Feed publishing step, do thefollowing:
- Publish a feedstory.
- Open up FacebookiOS app and check the feed story.
- Click on the storyattribution link and verify that your app is opened up.
Those are all the steps you need to take to set up and verifydistribution 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. ImplementFBSessionDelegate delegate method fdDidExtendToken and save the newtoken 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 [facebookextendAccessTokenIfNeede
- (void)applicationDidBecomeActive:(UIApplication *)application { [facebook extendAccessTokenIfNeede d];}
Note: Make sure you have the latest iOS SDK that includes supportfor extending access tokens.
Sample Apps
The Github repository contains a sample applications that showcaseFacebook Platform integration:
Hackbookfor iOS: includes SSO and sample API calls. This sample istargeted towards iOS developers who want to build social apps.
Wishlist:Open Graph sample to demonstrate the use of custom objects andactions in a mobile application.
- Facebook Share iOS Tutorial
- IOS 99乘法表
- ios BOKE
- iOS label
- The Python Tutorial 9. Classes
- Subversion - A Quick Tutorial
- Facebook 架构学习
-  
- The Python Tutorial 4. More Con…
- The Python Tutorial 6. Modules …
-
- IOS 单机 双击
- iOS NSString, N…
- iOS 蓝牙定位 iBeacons
- Custom TabBar for iOS
- iOS sqlite使用
- IOS Objective c 同步 异步链接 …
- Facebook's New Realtime Analytic…
- svn 常用命令《转》
- Linux中的环境设置PATH与exp…
- htaccess 的正则规则
- Improved logging in Objective-C …
- ShareKit 分享到FaceBook, Twitter…
- Facebook Share iOS Tutorial
- sqlplus: error while loading shared libraries
- 判断系统版本(用宏,非UIDevice)以…
- unsigned int的最大值及int的最大…
- 在ORACLE触发器里调用JAVA程序
- Property List 支持的数据类型(us…
- Shell编程基础《转》
- [知识学习]java中clone()的机制
- Xcode 调试加入参数《Apple Dev Do…