Facebook Share iOS Tutorial

iOS Tutorial

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

Facebook <wbr>Share <wbr>iOS <wbr>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.  Registering your iOS App with Facebook
     2.  Installing the iOS SDK
     3.  Implementing Single Sign-On
     4.  Adding Log Out to your App
     5.  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 and Deep Linking

Additional Topics:


Getting Started

Step 1: Registering your iOS App with Facebook

To begin integrating with the Facebook Platform, register your mobile website with Facebook and enter your 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 app in Xcode.

You application is now set up and you’re ready to begin integrating with Facebook!


Step 2: Installing the iOS SDK

Before you begin development with the Facebook iOS SDK, you will need to install the iOS dev tools, Git (the source control client we use for this SDK) and then clone the latest version of the SDK from GitHub:

Once you have everything installed you are now ready to set up your iOS app. First we will discuss Single Sign-On (SSO) which is a key implementation feature you should provide. After that section we will walk you through the steps of setting up an iOS app and enabling SSO.


Step 3: Implementing Single Sign-On (SSO)

One of the most compelling features of the iOS SDK is Single-Sign-On (SSO). SSO lets users sign into your app using their Facebook identity. If they are already signed into the Facebook iOS app on their device they do not have to even type a username and password. Further, because they are signing to your app with their Facebook identity, you can get permission from the user to access their profile information and social graph.

SSO primarily works by redirecting the user to the Facebook app on her device. Since the user is already logged into Facebook, they will not need to enter their username and password to identify themselves. They will see the auth dialog with the permissions that your app has asked for and if they allow then they will be redirected to your app with the appropriate access_token.

Developers should be aware that Facebook SSO will behave slightly different depending on what is installed on the user's device. This is what happens in certain configurations:

  • If the app is running in a version of iOS that supports multitasking, and if the device has the Facebook app of version 3.2.3 or greater installed, the SDK attempts to open the authorization dialog within the Facebook app. After the user grants or declines the authorization, the Facebook app redirects back to the calling app, passing the authorization token, expiration, and any other parameters the Facebook OAuth server may return.

  • If the device is running in a version of iOS that supports multitasking, but it doesn't have the Facebook app of version 3.2.3 or greater installed, the SDK will open the authorization dialog in Safari. After the user grants or revokes the authorization, Safari redirects back to the calling app. Similar to the Facebook app based authorization, this allows multiple apps to share the same Facebook user access_token through the Safari cookie.

  • If the app is running a version of iOS that does not support multitasking, the SDK uses the old mechanism of popping up an inline UIWebView, prompting the user to log in and grant access. The FBSessionDelegate is a callback interface that your app should implement: The delegate's methods will be invoked when the app successful logs in or logs out. Read the iOS SDK documentation for more details on this delegate.

We recommend that users update to the latest Facebook Application whenever possible.

Adding SSO support to your app is easy to do. So let's walk you through this.

Create your iOS Project

Open Xcode and create a new iOS project using the View-based Application project template. For the sake of simplicity, SSO functionality will be added to the application delegate that was created by Xcode when your app project was created.

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 build script 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-sdk folder (e.g. ~/facebook-ios-sdk/lib/facebook-ios-sdk). You may then drag the facebook-ios-sdk folder into the app Xcode project to include the iOS Facebook SDK static library.

Modify the application delegate header file

Step 1. Add an #import declaration to the application delegate header file to ensure that that the app can reference the SDK types in the app source files:

#import "FBConnect.h"

Step 2. Set the application delegate class to handle the Facebook session delegate callback by modifying the header file to add FBSessionDelegate to the list of delegates. For example for the MyGreatIOSApp:

@interface MyGreatIOSAppAppDelegate : NSObject 
    <UIApplicationDelegate, FBSessionDelegate>

Step 3. Set up the application delegate header file by creating instance variable:

Facebook *facebook;

Step 4. Add a property for an instance of the 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: method create instance of the Facebook class using your app ID (available from the Developer App):

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 and expiration date properties. This ensures that your app does not redirect to the facebook app and invoke the auth dialog if the app already has a valid access_token. If you have asked for offline_access extended permission then your access_token will not expire, but can still get invalidated if the user changes their password or uninstalls your app. More information here. Note: offline_access is deprecated. See the Extending the access token section for information on how to extend the expiration time of an access token for active users 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 valid call the authorize method which will both log the user in and prompt the user to authorize the app:

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

Step 5. Add the application:handleOpenURL: and application:openURL: methods with 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 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];

}

iOS Impl

Modify the app property list file

The last thing that needs to be accomplished to enable SSO support is a change to the .plist file that handles configuration for the app. Xcode creates this file automatically when the project is created. A specific URL needs to be registered in this file that uniquely identifies the app with iOS. Create a new row named URL types with a single item, URL Schemes, containing a single value, fbYOUR_APP_ID (the literal characters fb followed by your app ID). The following shows exactly how the row should appear in the .plist file:

iOS Impl

That is it. SSO is ready to go. All that remains is to build and debug the app to ensure anything is setup up correctly.

Test your app

You can test SSO using either your simulator or a device. If you use a simulator you should make sure you log in to Facebook on the mobile browser. To test on the device make sure you are currently logged in to the Facebook app. Initially you can test on a simulator.

Build and run your app from Xcode. When the app starts in the emulator, you should see the following dialog:

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

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


Step 4: Adding Log Out to your App

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

[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'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 "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 theapplication: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.


Step 5: Requesting Additional Permissions

By default, the user is asked to authorize the app to access basic information that is available publicly or by default on Facebook. If your app needs more than this basic information to function, you must request specific permissions from the user. This is accomplished by passing a NSArray 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.

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

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


Adding Social Context

Step 6: Using the Graph API

The Facebook Graph API presents a simple, consistent view of the Facebook social graph, uniformly representing objects in the graph (e.g., people, photos, events, and fan pages) and the connections between them (e.g., friend relationships, shared content, and photo tags).

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

Note that the server response will be in JSON string format. The SDK uses an open source JSON libraryhttps://github.com/stig/json-framework/ to parse the result. If a parsing error occurs, the SDK will callbackrequest: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.


Step 7: Integrating with Social Channels

Social Channels enable users to post to their friends' News Feed or send a Request to their friends. The iOS SDK provides a method for integrating social channels through Facebook Platform dialogs. The currently supported dialogs are:

  • 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 user’s 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:

    [facebook dialog:@"feed" andDelegate:self];

Timeline and Open Graph

Historically, Facebook has managed this graph and has expanded it over time as we launch new products (photos, places, etc.). In 2010, we extended the social graph, via the Open Graph protocol, to include 3rd party web sites and pages that people liked throughout the web. We are now extending the Open Graph to include arbitrary actions and objects created by 3rd party apps and enabling these apps to integrate deeply into the Facebook experience.

After a user adds your app to their Timeline, app specific actions are shared on Facebook via the Open Graph. As your app becomes an important part of how users express themselves, these actions are more prominently displayed throughout the Facebook Timeline and News Feed. This enables your app to become a key part of the user's and their friend's experience on Facebook.

Timeline is coming to mobile soon. In preparation, you can start integrating now.

To learn more about how you can integrate your app into Open Graph and Timeline, learn more or dive right intothe tutorial.


Advanced Configuration

Step 8: Sharing an App ID across Multiple Apps

You can use one app ID across multiple apps. One scenario where you may want to do this is if you have a free and paid version of your iOS app. Facebook allows you to define a URL Scheme Suffix parameter, urlSchemeSuffix, that you pass on to the app initWithAppId:urlSchemeSuffix:andDelegate: method. The second and last step you do is append this urlSchemeSuffix to the SSO callback URL defined in the .plist file.

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

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

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

Step 2. Modify the unique URL in the .plist file

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

iOS Impl

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.

iOS Impl

The order in which you list the suffixes determines the order that the Facebook app will search for the installed app when linking to your app. For example, if you list two URL Scheme Suffix entries, ''freeapp'' (for your free app) and ''paidapp'' (for your paid app), then the Facebook app will first look for the free app then the paid app. If you want the Facebook app to look for the paid app first, then put the corresponding suffix first in the list.


Step 9: Setting up for Facebook iOS App Distribution and Deep Linking

If your app is SSO-enabled then you can get distribution through the Facebook iOS app. The following diagram shows how this distribution flows from when a user first interacts with a 3rd party app, publishes a news story or sends an app request, to how these stories and request notifications drive back to your app. The diagram also shows how app search and bookmarks can drive distribution from the Facebook app.

iOS Header

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: orapplication:openURL:sourceApplication:annotation: methods in the app delegate implementation file to customize how your app will handle these notifications.

If the user has your application installed, and has authenticated your app with Facebook, here is the URL we open:

fb[app id]://authorize#expires_in=0&access_token=[token]&target_url=[Linked URL]

If the app is installed, but the user has not authenticated it with Facebook, the URL format is:

fb[app id]://authorize#target_url=[Linked URL]

To summarize, these are the channels that can drive distribution back to your app:

  • App search: your app will be visible if it passes an active usage threshold.
  • App bookmarks: your app will be visible to users who have previously used it and based on a usage threshold.
  • App request notifications: requests 2.0 notifications sent to a friend will link back to your app.
  • Story attribution: your app source attribution will be visible if you set up your app with a namespace.
  • Story links: you can configure links in your News Feed stories that will point back to your app.

Let's walk through a tutorial of setting up and verifying Facebook app distribution.

Step 1. Configure your app settings in the Developer App:

iOS Bookmarks

iOS Bookmarks

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 and through search results. Make sure that you turn this on after you have properly implemented SSO.
  5. iOS native deep linking - you must enable this setting if you want your app to be linked to from News Stories. You must also enable the Configured for iOS SSO setting to turn on this feature. If you wish to handle your own News Story links then disable this setting.
  6. 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.
  7. 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.

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

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

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

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.

Facebook <wbr>Share <wbr>iOS <wbr>Tutorial
  • Modify MyGreatIOSAppAppDelegate.h file from the previous tutorial and add FBDialogDelegate to the list of supported protocols:

    @interface MyGreatIOSAppAppDelegate : NSObject 
        <UIApplicationDelegate, 
        FBSessionDelegate, FBDialogDelegate> {
        Facebook *facebook;    
    }
    
    
  • Modify MyGreatIOSAppAppDelegate.m file from the previous tutorial and add the following code to the beginning of the application:didFinishLaunchingWithOptions: method:

    // Add the requests dialog button
    UIButton *requestDialogButton = [UIButton 
                                        buttonWithType:UIButtonTypeRoundedRect];
    requestDialogButton.frame = CGRectMake(40, 150, 200, 40);
    [requestDialogButton setTitle:@"Send Request" forState:UIControlStateNormal];
    [requestDialogButton addTarget:self 
        action:@selector(requestDialogButtonClicked)
        forControlEvents:UIControlEventTouchUpInside];
    [self.viewController.view addSubview:requestDialogButton];
    
    
  • Modify MyGreatIOSAppAppDelegate.m file from the previous tutorial and add the following new method:

    // Method that gets called when the request dialog button is pressed
    - (void) 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:

When you have enabled iOS native deep linking in the Dev app, published stories on Facebook for iOS will link back to your app if they have it installed, or the Apple App Store if they do not. Facebook will apply re-writing rules to redirect these links back to your app. See here to see how you can implement deep linking so users go to the correct content in 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",
                @"http://www.example.com/", @"link",
                @"http://fbrell.com/f8.jpg", @"picture",
                nil];  
        [facebook dialog:@"feed"
                andParams:params
              andDelegate:self];
    }
    
    
  • In your code, replace www.example.com with a link to your website.

  • Build and run your sample app.
  • Publish a feed story.
  • Open up Facebook iOS app and check the feed story.
  • Click on the story link and verify that your app launches.

Step 6. Exercise the app story attribution flow:

When you publish a News Story there will be an app attribution linked to it. If you have configured SSO support then if a user clicks on the "via YOUR_APP" link they will be directed to your app.

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

If you completed the previous New Feed publishing step, do the following:

  • Publish a feed story.
  • Open up Facebook iOS app and check the feed story.
  • Click on the story attribution link and verify that your app is opened up.

Those are all the steps you need to take to set up and verify distribution through Facebook iOS app.


Additional Topics

Handle Errors

Errors are handled by the FBRequestDelegate and FBDialogDelegate interfaces. Apps can implement these interfaces and specify delegates as necessary to handle any errors.

Read more about error handling in the iOS reference documentation.


Extending the Access Token

Step 1. Implement FBSessionDelegate delegate method fdDidExtendToken and save the new token and expiration time. Here is an example:

-(void)fbDidExtendToken:(NSString *)accessToken expiresAt:(NSDate *)expiresAt {
    NSLog(@"token extended");
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:accessToken forKey:@"FBAccessTokenKey"];
    [defaults setObject:expiresAt forKey:@"FBExpirationDateKey"];
    [defaults synchronize];
}

Step 2. Call [facebook extendAccessTokenIfNeeded] in your AppDelegate method applicationDidBecomeActive. The SDK attempts to refresh its access tokens when it makes API calls, but it's a good practice to refresh the 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 support for extending access tokens.


Sample Apps

The Github repository contains a sample applications that showcase Facebook Platform integration:

  • Hackbook for iOS: includes SSO and sample API calls. This sample is targeted towards iOS developers who want to build social apps.

  • Wishlist: Open Graph sample to demonstrate the use of custom objects and actions in a mobile application.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值