Facebook Share iOS Tutorial

来源:互联网 发布:手机淘宝5.9.9官方版 编辑:程序博客网 时间:2024/05/30 04:59

iOS Tutorial

(http://developers.facebook.com/docs/mobile/ios/build/#register)

GettingStarted › Mobile › iOSTutorial
Facebook <wbr>Share <wbr>iOS <wbr>Tutorial

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:

     1.  Registeringyour iOS App with Facebook
     2.  Installingthe iOS SDK
     3.  ImplementingSingle Sign-On
     4.  AddingLog Out to your App
     5.  RequestingAdditional Permissions

Adding SocialContext:

     6.  Usingthe Graph API
     7.  Integratingwith Social Channels

AdvancedConfiguration:

     8.  Sharingan App ID across Multiple Apps
     9.  Settingup for Facebook iOS App Distribution and Deep Linking

Additional Topics:

  • HandleErrors
  • Extendingthe Access Token
  • SampleApps

Getting Started

Step 1: Registering your iOS App with Facebook

To begin integrating with the FacebookPlatform, registeryour mobile website with Facebook and enteryour app's basic information.

Facebook <wbr>Share <wbr>iOS <wbr>Tutorial


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 GitHub:

  • 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 Single-Sign-On (SSO). SSO lets userssign into your app using their Facebook identity. If they arealready signed into the Facebook iOS app on their device they donot have to even type a username and password. Further, becausethey are signing to your app with their Facebook identity, you canget permission from the user to access their profile informationand social graph.

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 View-basedApplication project template. For thesake of simplicity, SSO functionality will be added to theapplication delegate that was created by Xcode when your appproject was created.

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 buildscript found under the scriptsdirectory,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 declarationto the application delegate header file to ensure that that the appcan reference the SDK types in the app source files:

#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 Facebook class:

@property (nonatomic, retain) Facebook *facebook;

iOS Header

Modify the application delegate implementation file

Step 1. Synthesize the facebook property(this creates getter and setter methods):

@synthesize facebook;

Step 2. Within the body of the application:didFinishLaunchingWithOptions: methodcreate instance of the Facebook class using your app ID (availablefrom the DeveloperApp):

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 accesstoken and expiration date properties. This ensures that your appdoes not redirect to the facebook app and invoke the auth dialog ifthe app already has a valid access_token.If you have asked for offline_access extendedpermission then your access_token will not expire, but can stillget invalidated if the user changes their password or uninstallsyour app. More information here.Note: offline_access is deprecated. Seethe Extendingthe access token section for information onhow to extend the expiration time of an access token for activeusers of your app.

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 methodwhich will both log the user in and prompt the user to authorizethe app:

if (![facebook isSessionValid]) {    [facebook authorize:nil];}

Step 5. Add the application:handleOpenURL: and application:openURL: methodswith a call to thefacebook instance:

// 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: providesthe app with the user's credentials.

Step 6. Implement the fbDidLogin methodfrom the FBSessionDelegate implementation.In this method you will save the user's credentials specificallythe access token and corresponding expiration date. For simplicityyou 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];}

iOS Impl

Modify the app property list file

The last thing that needs to be accomplished to enable SSO supportis a change to the .plist filethat handles configuration for the app. Xcode creates this fileautomatically when the project is created. A specific URL needs tobe registered in this file that uniquely identifies the app withiOS. Create a new row named URL types with asingle item, URL Schemes, containing a singlevalue, fbYOUR_APP_ID (theliteral characters fb followed by yourapp ID). The following shows exactly how the row should appear inthe .plist file:

iOS Impl

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:

Facebook <wbr>Share <wbr>iOS <wbr>Tutorial

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 Allow, your app is authorized and youwill have access to the user's profile and social graph throughthe facebook instance.If the user presses Don't Allow, your app is notauthorized and you will not have access to the user's data.


Step 4: Adding Log Out to your App

When the user wants to stop using Facebook integration with yourapp, you can call the logout methodto clear the app state and make a server request to invalidate thecurrent access_token.

[facebook logout];

You may implement the fbDidLogout methodof the FBSessionDelegate protocolto handle any post-logout actions you wish to take.

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 "Applications,Games, and Websites" tab of their Facebook privacy settingsdashboard. You can also revoke an app's permissionsprogrammatically using a GraphAPI call.

Now add a logout button and handler to your sample app.

Step 1. Add the logoutbutton and handler:

Modify MyGreatIOSAppAppDelegate.m file from the tutorial and addthe following code to the beginning of theapplication:didFinishLaunchingWithOptions: method:

// 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 methodwhen the button is tapped. Modify MyGreatIOSAppAppDelegate.m filefrom 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 logoutcallback handler:

Modify MyGreatIOSAppAppDelegate.m file from the previous tutorialand add the FBSessionDelegate callbackmethod 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. 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 ofpermissions to the authorize method.The following example shows how to ask for access to pages a userhas 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 thefirst authorization screen. In our example this isthe user_likes permission.Extended permissions will be requested in the second authorizationscreen. In our example this is the read_stream permissions.You can refer to the permissionsguide for more information.

Facebook <wbr>Share <wbr>iOS <wbr>TutorialFacebook <wbr>Share <wbr>iOS <wbr>Tutorial

A full list of permissions is available inour permissionsreference. There is a strong inverse correlation between thenumber of permissions your app requests and the number of usersthat will allow those permissions. The greater the number ofpermissions you ask for, the lower the number of users that willgrant them; so we recommend that you only request the permissionsyou absolutely need for your app.

Let's go ahead and test this out. Modify the tutorial's appdelegate implementation file to see this in action. Intheauthorize 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 theauthorization dialogs for the permissions you have requested.


Adding Social Context

Step 6: Using the Graph API

The Facebook GraphAPI presents a simple, consistent view of theFacebook social graph, uniformly representing objects in the graph(e.g., people, photos, events, and fan pages) and the connectionsbetween them (e.g., friend relationships, shared content, and phototags).

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 interfaceto handle your request responses.

Note that the server response will be in JSON string format. TheSDK uses an open source JSON libraryhttps://github.com/stig/json-framework/ toparse the result. If a parsing error occurs, the SDK willcallbackrequest:didFailWithError: inyour delegate.

A successful request will callback request:didLoad: inyour delegate. The result passed to your delegate can bean NSArray,if there are multiple results, or an NSDictionary ifthere is only a single result.

Advanced apps may want to provide their own custom parsing and/orerror handling, depending on their individual needs.

Read the iOSSDK documentation for more details onthe FBRequestDelegate delegate.


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 FacebookPlatform dialogs. The currently supported dialogs are:

  • 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 mobiledistribution guide for details on supportedSocial Channels.

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 Requestdialog. If the user’s device supports it, they will receive aPush Notification via the Facebook native app whenever a friendsends them a request, in addition to the notification they normallyget within Facebook.

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 FeedDialog.

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, learnmore or dive right intothetutorial.


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: method.The second and last step you do is appendthis urlSchemeSuffix tothe SSO callback URL defined in the .plist file.

Note: The URL SchemeSuffix must be lowercase and contain only letters.

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: method,pass in the URL Scheme Suffix.

facebook = [[Facebook alloc] initWithAppId:@"YOUR_APP_ID"                            urlSchemeSuffix:@"foo"                                andDelegate:self];

Step 2. Modify theunique URL in the .plist file

Modify the URL Schemes entry from fbYOUR_APP_ID to fbYOUR_APP_IDYOUR_URL_SCHEME_SUFFIX (theliteral characters fb followed by your app ID then by your URLScheme Suffix). For example, if your app ID is "1234" your new URLshould be fb1234foo.

iOS Impl

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 Facebookdistribution to your app. If you have multipleapps using a single Facebook app ID you will need to add aconfiguration to the DevApp to list the URL Scheme Suffix informationfor the apps that share one ID.

iOS Impl

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.

iOS Header

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 parameterof the callback link. You can modifythe application:handleOpenURL: orapplication:openURL:sourceApplication:annotation: methodsin the app delegate implementation file to customize how your appwill handle these notifications.

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 DeveloperApp:

iOS Bookmarks

iOS Bookmarks

Make the following changes to your app's basic settings:

  1. AppNamespace - Set a unique namespace for yourapp. This namespace can be used for configuring story links back toyour site.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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.
  7. 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 willbe passed to your app which means that the user will beauthenticated when your app is launched. If the user has notauthorized your app then no access_token willbe passed to your app and the user will not be authenticated whenyour app is launched.

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.

Facebook <wbr>Share <wbr>iOS <wbr>Tutorial

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 valid)if you had previously authorized the app.

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.

Facebook <wbr>Share <wbr>iOS <wbr>Tutorial

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 valid)if you had previously authorized the app.

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.

Facebook <wbr>Share <wbr>iOS <wbr>Tutorial
  • 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:didFinishLaunchingWithOptions: 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(requestDialogButtonClicked)    forControlEvents:UIControlEventTouchUpInside];[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) 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 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 in the Dev app,published stories on Facebookfor iOS will link back to your app if theyhave it installed, or the Apple App Store if they do not. Facebookwill apply re-writing rules to redirect these links back to yourapp. See here tosee how you can implement deep linking so users go to the correctcontent in your app.

  • Modify MyGreatIOSAppAppDelegate.m file from the previous tutorialand add the following code to the beginning ofthe application:didFinishLaunchingWithOptions: 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:UIControlEventTouchUpInside];    [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 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 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.

Facebook <wbr>Share <wbr>iOS <wbr>Tutorial

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 and FBDialogDelegate interfaces.Apps can implement these interfaces and specify delegates asnecessary to handle any errors.

Read more about error handling in the iOSreference documentation.


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 [facebookextendAccessTokenIfNeeded] in your AppDelegate methodapplicationDidBecomeActive. The SDK attempts to refresh its accesstokens when it makes API calls, but it's a good practice to refreshthe access token also when the app becomes active.

- (void)applicationDidBecomeActive:(UIApplication *)application {    [facebook extendAccessTokenIfNeeded];}

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.

0 0
原创粉丝点击