Messenger SDK for iOS

Send images, animated gifs, videos and audio clips to Messenger from your iOS app

Implementation in iOS

With the SDK for Messenger your app can share images, animated gifs, videos, and audio clips. This SDK enables basic integration and optimized integration.

Be sure to add analytics so that you can get metrics and measure the performance of your integration.

Prerequisites

Step 1: Get a Facebook App ID

You will need a Facebook App ID so if you don't already have one, create one.

Step 2: Add the SDK to your project

Messenger is included in the download for Facebook SDK for iOS. Install the package and the SDK will be placed into ~/Documents/FacebookSDK. In that folder you will find FBSDKMessengerShareKit.framework which you should add to your project.

Read more about getting started with the iOS SDK.

Step 3: Configure your Xcode project

Follow the setup process to properly configure your Info.plist and be sure you set values for FacebookAppID and URL types as instructed. Also, provide your Bundle Identifier from Step 1. Take note of your App ID.

If you already have a Facebook App, be sure that your Info.plist is properly configured as stated above. Here is a more detailed explanation.

Configure your .plist fileConfigure your .plist file for iOS 9

Step 4: Configure the iOS Settings

In your Facebook app settings, add the iOS platform if it doesn't exist already. Be sure to set the Bundle ID corresponding to your XCode project from Step 1. If your app is live, set the iPhone Store ID. Otherwise, leave this field blank for now and set it once your app is live in the App Store.

If you ever modify your Bundle ID, update your Facebook app settings. Apps that are improperly configured may encounters errors when sharing. Content may not display attribution. You may find it useful to use the Device Console in Xcode to see detailed error information.

Step 5: Import the SDK

In order to import the SDK, add the following include.

#import <FBSDKMessengerShareKit/FBSDKMessengerShareKit.h>

Step 6: Setup your test users

Be sure that the users you are testing with have a role in your Facebook app. This is set in App Settings in the Roles section. If your app is in Development Mode, the buttons under the content will only appear to users who have a role (Administrators, Developers, and Testers) in your Facebook app .

Basic integration

Sharing content

The SDK provides simple function for sharing images, animated gifs, videos, and audio clips.

Sharing an image:

UIImage *image = [UIImage imageNamed:@"selfie_pic"];
[FBSDKMessengerSharer shareImage:image withOptions:nil];
NSString *filepath = [[NSBundle mainBundle] pathForResource:@"corgi" ofType:@"webp"];
NSData *webpData = [NSData dataWithContentsOfFile:filepath];
[FBSDKMessengerSharer shareAnimatedWebP:webpData withOptions:nil];

Sharing an animated gif:

NSString *filepath = [[NSBundle mainBundle] pathForResource:@"selfie_gif" ofType:@"gif"];
NSData *gifData = [NSData dataWithContentsOfFile:filepath];
[FBSDKMessengerSharer shareAnimatedGIF:gifData withOptions:nil];

Sharing a video:

NSString *filepath = [[NSBundle mainBundle] pathForResource:@"selfie_vid" ofType:@"mp4"];
NSData *videoData = [NSData dataWithContentsOfFile:filepath];
[FBSDKMessengerSharer shareVideo:videoData withOptions:nil];

Sharing an audio clip:

NSString *filepath = [[NSBundle mainBundle] pathForResource:@"selfie" ofType:@"mp3"];
NSData *mp3Data = [NSData dataWithContentsOfFile:filepath];
[FBSDKMessengerSharer shareAudio:mp3Data withOptions:nil];

In the middle image, the content is rendered with a border. In the last image, the content is rendered without a border. In some cases, you may want to render your content without a border (e.g., stickers, animated gifs with transparent background). In order to do this, set the option as follows:

// An example of sharing an image without a border.
FBSDKMessengerShareOptions *options = [[FBSDKMessengerShareOptions alloc] init];
options.renderAsSticker = YES;

[FBSDKMessengerSharer shareImage:image withOptions:options];

You may otherwise ignore the withOptions parameter unless you're doing an optimized integration.

Supported formats:

  • Images should be type UIImage and conform to Apple's standards.
  • Videos should be 30 seconds or less in duration.

Using Messenger buttons

We've provided Messenger buttons in the SDK that you can use in your integration. If you're doing an optimized integration you are required to use these buttons.

If you're doing an optimized integration you must use the buttons provided in the SDK.


FBSDKMessengerShareButton creates UIButton's styled specifically to send to Messenger. These buttons can be styled with FBSDKMessengerShareButtonStyle as blue, white with a blue border, and borderless white.

Rectangular button:

// Create a UIButton styled for sharing to messenger. You can leave 
// the size at its default (365, 45) or change the size yourself
UIButton *button = [FBSDKMessengerShareButton rectangularButtonWithStyle:FBSDKMessengerShareButtonStyleBlue];
[button addTarget:self action:@selector(_shareButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];

Circular button:

//Define the size of the circular button at creation time
CGFloat buttonWidth = 50;
UIButton *button = [FBSDKMessengerShareButton circularButtonWithStyle:FBSDKMessengerShareButtonStyleBlue
                                                                width:buttonWidth];
[button addTarget:self action:@selector(_shareButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];

You will need to provide translation for the button:

NSLocalizedString(@"Send", @"Button label for sending a message")

Optimized integration

App can integrate more deeply to enable options for discovery and engagement. Apps that have been approved for optimized sharing may be also be featured in the composer to help discovery.

Read more about the different levels of integration.

Setup

In order to show the Reply button on the messages, you must set the iPhone Store ID field as indicated in Step 4 of Setup.

Handling calls from Messenger

Messenger may call your app to compose content. This may be from the composer or the "Reply" button which appears on content.

In order to handle this, define or add the following to check to your AppDelegate.m:

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{

  // Check if the handler knows what to do with this url 
  if ([_messengerUrlHandler canOpenURL:url sourceApplication:sourceApplication]) {
    // Handle the url
    [_messengerUrlHandler openURL:url sourceApplication:sourceApplication];
  }

  return YES;
}

And then call the share function as state above. For example,

[FBSDKMessengerSharer shareImage:image withOptions:nil];

Now your app will properly support the compose and reply flow. Messenger will determine whether the person see the broadcast experience (which features a preview of the content and friend picker) or the reply experience (sheet with inline content).

Advanced flow control

In some cases, you may want to override the default flow behavior. For example, people may enter your app through a reply flow, but you may want the subsequent share to happen with a send flow, perhaps because they put your app into the background and returned much later with a different intent.

You can do this by passing options to the share methods. This requires retaining context objects that are passed to the delegate.

Include the framework in your AppDelegate.m, indicate that your delegate conforms to the FBSDKMessengerURLHandlerDelegate protocol and add the following methods:

#import <FBSDKMessengerShareKit/FBSDKMessengerShareKit.h>

@interface AppDelegate () <FBSDKMessengerURLHandlerDelegate>
@end

/*
 * Initialize the handler and set self as the delegate.
 */
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

  _messengerUrlHandler = [[FBSDKMessengerURLHandler alloc] init];
  _messengerUrlHandler.delegate = self;
  
  return YES;
}

/*
 * When people enter your app through the composer in Messenger, 
 * this delegate function will be called.
 */
- (void)messengerURLHandler:(FBSDKMessengerURLHandler *)messengerURLHandler
  didHandleOpenFromComposerWithContext:(FBSDKMessengerURLHandlerOpenFromComposerContext *)context;
{
  _composerContext = context;
}

/*
 * When people enter your app through the "Reply" button on content
 * this delegate function will be called.
 */
- (void)messengerURLHandler:(FBSDKMessengerURLHandler *)messengerURLHandler
  didHandleReplyWithContext:(FBSDKMessengerURLHandlerReplyContext *)context;
{
  _replyContext = context;
}

Retain the FBSDKMessengerURLHandlerOpenFromComposerContext and the FBSDKMessengerURLHandlerReplyContext. Read below to see how they are used.

When sharing content back to Messenger, pass in the options:

NSString *metadata = @"{ \"image\" : \"pedro\" }";
UIImage *image = [UIImage imageNamed:@"selfie_pic"];

// getContextForShareMode is a helper method 
FBSDKMessengerShareOptions *options = [[FBSDKMessengerShareOptions alloc] init];
options.metadata = metadata;
options.contextOverride = [self getContextForShareMode];

[FBSDKMessengerSharer shareImage:image withOptions:options];

metadata field

You can see that we're passing options to the share method. This contains two fields we want to send back to Messenger: metadata and contextOverride.

The metadata field takes a NSString and is optional. It can be used to give information about the content being shared. For example, you can store a serialized JSON string. This is useful during replies as this data is passed back to your app.

See best practice on using metadata.

contextOverride field

The contextOverride field takes a FBSDKMessengerShareOptions object and is optional. If this is nil, the default SDK behavior will take over.

Here is getContextForShareMode which is an helper method I created as an example:

// Below is all example code.

// helper enum i made to define the state 
enum MessengerShareMode { MessengerShareModeSend, 
                          MessengerShareModeComposer,
                          MessengerShareModeReply};

// shareMode holds state indicating which flow the user is in.
// Return the corresponding FBSDKMessengerContext based on that state.
enum MessengerShareMode shareMode;

...

- (FBSDKMessengerContext *) getContextForShareMode
{
  // shareMode holds state indicating which flow the user is in.
  // Return the corresponding FBSDKMessengerContext based on that state.

  if (shareMode == MessengerShareModeSend) {    
    // Force a send flow by returning a broadcast context.
    return [[FBSDKMessengerBroadcastContext alloc] init];

  } else if (shareMode == MessengerShareModeComposer) {
    // Force the composer flow by returning the composer context.    
    return _composerContext;

  } else if (shareMode == MessengerShareModeReply) {
    // Force the reply flow by returning the reply context.    
    return _replyContext;
  }
  
  
  return nil;
}

Read the best practice on handling compose and reply flows.

Accessing metadata and participant user IDs

During a reply, the metadata is passed back to you in the FBSDKMessengerURLHandlerReplyContext. Also, the user ids of the participants in the thread may be available. You will only receive user ids of people who have allowed personalized replies and are logged into Facebook in your app. We present this dialog in Messenger only if we detect they've logged in previously.

You can access this data in this call to the delegate:

- (void)messengerURLHandler:(FBSDKMessengerURLHandler *)messengerURLHandler
  didHandleReplyWithContext:(FBSDKMessengerURLHandlerReplyContext *)context
{
  // Accessing the metadata that was originally sent with the content
  NSString *metadata = context.metadata;
  
  // IDs of the other users on the thread who are also logged into this app
  NSSet *userIds = context.userIDs;

}

See best practice on using participant IDs to personalize with Facebook Login.

Back-to-Messenger button

Messenger may call your app to compose content. In this flow, we encourage you to provide an easy way for the person to return to Messenger.

In order to do this, call the following:

[FBSDKMessengerSharer openMessenger];

We've provided assets for the button:

Download button assets

Analytics

When doing an optimized integration, you must also track app activations using analytics.

Technical Best Practices

These best practices only apply to optimized integrations.

Design metadata for multiple versions

Consider how you structure your metadata. If you ship successive versions of your app, you may have multiple versions of your app live. Future-proof your app by using data in a way that's forward and backward compatible. For example, you could use a JSON structure for storing information and include a version tag to know which fields it contains.

Allow the person to return to Messenger

When a person enters your app through Messenger, you should provide a button or other way for the person to easily return. We've provided code and assets to do this.

Handle send flow vs reply flow

If a person enters your app directly, upon send they will enter a flow in Messenger where they can select the recipients. If a person enters your app via Messenger, upon send they will enter a flow where their content is rendered inline a conversation.

This send vs reply behavior depends on whether the context (FBSDKMessengerURLHandlerOpenFromComposerContext, FBSDKMessengerURLHandlerReplyContext) is passed on share. If the context is nil, the person will go through the send flow. If the context is set, the person will go through the reply flow.

You may want to handle scenarios where a person exits a reply flow and enters the send flow in your app. For example, during the reply flow the person leaves your app and returns much later, directly to your app. You may want to put that into the send flow by omitting the context on the following share.

Use Facebook Login to create personalized experiences

By integrating Login into your app, you can receive the user IDs of the people in a conversation. This enables you to create content personalized for that set of people. For example, you could show a sticker pack containing rivals teams of people in the chat.

Analytics

In order to record metrics from your integration, call the following App Event. Note that you will need to import the Facebook SDK into your project. Add the following to your AppDelegate.m:

#import <FacebookSDK/FacebookSDK.h>

- (void)applicationDidBecomeActive:(UIApplication *)application {

    // Call the 'activateApp' method to log an app event for use
    // in analytics and advertising reporting.
    [FBSDKAppEvents activateApp];

    ...
}

You must integrate analytics and track app activations if you're submitting an optimized integration.


Read more details about App Events in iOS.

Releasing your app

There are a few things to keep in mind as you prepare your app for release.

Attribution

When content is shared into Messenger, your app icon and name will appear under your content. This is your App Icon and Display Name in your app settings.

If your app is in Development Mode, attribution will only appear to users who have a role in your Facebook app (Administrators, Developers, and Testers). When your app is made public, attribution will appear for the general public.

iPhone Store ID

The iPhone Store ID field in the app settings can only be set with apps that are live in the App Store. Be sure to set this field after your app is live.