Skip to content
Titanium SDK

facebook

Support for the native Facebook SDK in Titanium using JavaScript

15.0.0AndroidiOSNov 23, 2024

Install

A module is a zip you unpack in your project. There is no installer command yet - a ti module install is planned but does not exist today, so the steps below are the ones that work.

  1. 1. Download the release archive

  2. 2. Unpack it at your project root

    cd /path/to/your-project
    unzip ~/Downloads/facebook-android-15.0.0.zip
    unzip ~/Downloads/facebook-iphone-15.0.0.zip

    The archive already contains the full path, so it lands in place:

    • modules/android/facebook/15.0.0/
    • modules/iphone/facebook/15.0.0/
  3. 3. Add it to tiapp.xml

    <modules>
      <module platform="android" version="15.0.0">facebook</module>
      <module platform="iphone" version="15.0.0">facebook</module>
    </modules>

    The platform attribute is the packager’s name for the platform, which is iphone for iOS - the same word the archive uses in its own path.

  4. 4. Require it from your app

    const mod = require('facebook');

Manifest

Android 15.0.0

Minimum SDK
13.0.0
Module API version
4
Architectures
arm64-v8a, armeabi-v7a, x86, x86_64
GUID
e4f7ac61-1ee7-44c5-bc27-fa6876e2dce9
Author
Mark Mokryn and Ashraf A. S. (Appcelerator)
License
Apache License Version 2.0
Copyright
Copyright (c) 2014 by Mark Mokryn, Copyright (c) 2009-present by Axway Inc.

iOS 15.0.0

Minimum SDK
11.0.0
Module API version
2
Architectures
arm64, x86_64
GUID
e4f7ac61-1ee7-44c5-bc27-fa6876e2dce9
Author
Mark Mokryn, Ng Chee Kiat and Hans Knoechel
License
Apache License Version 2.0
Copyright
Copyright (c) 2009-present by Axway Appcelerator
Mac Catalyst
supported

API reference

Compiled from tidev/ti.facebook@15.0.0 (ec3e7a7).

Modules.Facebook

moduleAndroidiPhoneiPadsince 3.1.0

Extends Titanium.Module

Add-on Facebook module.

The Facebook module is used for connecting your application with Facebook. This module supports the following features:

  • Logging in to Facebook and authorizing your application with either the Login button or programatically.

  • Making requests through the Facebook Graph API using the requestWithGraphPath() method.

Getting Started

To use the Facebook module, you need a Facebook application. To create a Facebook App, go to the Facebook Developer App: developers.facebook.com/apps.

  • Edit the modules section of your tiapp.xml file to include this module:

    [modules](api:Modules)
        <!-- Add the appropriate line(s) to your modules section -->
        <module platform="android">facebook</module>
        <module platform="iphone">facebook</module>
    </modules>
  • Instantiate the module with the require('facebook') method, then make subsequent API calls with the new Facebook object.

    var fb = require('facebook');
    fb.permissions = [FACEBOOK_APP_PERMISSIONS]; // e.g. ['email']
    fb.initialize();
    fb.authorize();

Additional iOS Setup Steps

For the iOS platform, in the ios plist dict section of your tiapp.xml file, add the following keys:

  • FacebookAppID key with your Facebook App ID as the string value
  • FacebookDisplayName key with your Facebook App name (the one from developer.facebook.com) as the string value
  • CFBundleURLTypes key with a single-element array containing a dict as the value, where the dict contains:
    • CFBundleURLName key with the application app ID (same value as the id in the tiapp.xml file) as the string value
    • CFBundleURLSchemes key with a single-element array containing the Facebook App ID prefixed with fb as a string value

For example:

<ti:app>
    <ios>
        <plist>
            <dict>
                <key>CFBundleURLTypes</key>
                <array>
                    <dict>
                        <key>CFBundleURLName</key>
                        <!-- Application ID same as the id value in the tiapp.xml file -->
                        [string](api:Global.String)APP_ID</string>
                        <key>CFBundleURLSchemes</key>
                        <array>
                            <!-- Prefix the Facebook App ID with 'fb' -->
                            [string](api:Global.String)fbFACEBOOK_APP_ID</string>
                        </array>
                    </dict>
                </array>
                <key>FacebookAppID</key>
                <!-- Facebook App ID -->
                [string](api:Global.String)FACEBOOK_APP_ID</string>
                <key>FacebookDisplayName</key>
                <!-- Facebook App Name from developer.facebook.com -->
                [string](api:Global.String)FACEBOOK_APP_NAME</string>
            </dict>
        </plist>
    </ios>
</ti:app>

To enable the use of Facebook dialogs (e.g., Login, Share), you also need to include the following key and values in tiapp.xml to handle the switching in and out of your app:

<key>LSApplicationQueriesSchemes</key>
<array>
    [string](api:Global.String)fbapi</string>
    [string](api:Global.String)fb-messenger-api</string>
    [string](api:Global.String)fbauth2</string>
    [string](api:Global.String)fbshareextension</string>
</array>

If you choose to enable App Transport Security (ATS), you have to set the following keys and values in tiapp.xml <ios> section for facebook module:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
        <dict>
            <key>facebook.com</key>
            <dict>
                <key>NSIncludesSubdomains</key> 
                <true/>
                <key>NSExceptionRequiresForwardSecrecy</key> 
                <false/>
            </dict>
            <key>fbcdn.net</key>
            <dict>
                <key>NSIncludesSubdomains</key> 
                <true/>
                <key>NSExceptionRequiresForwardSecrecy</key>  
                <false/>
            </dict>
            <key>akamaihd.net</key>
            <dict>
                <key>NSIncludesSubdomains</key> 
                <true/>
                <key>NSExceptionRequiresForwardSecrecy</key> 
                <false/>
            </dict>
        </dict>
</dict>

Additional Android Setup Steps

For the Android platform, you need to:

  • Add the Facebook Login activity to the Android manifest
  • Add the Facebook App ID to the Android resources string.xml file
  • Create a Facebook proxy and associate it with the current active activity

Modify the Android Manifest

Add the Facebook Login activity to the android manifest section of your tiapp.xml file. You may need to add the manifest and application elements.

<ti:app>
    <android xmlns:android="http://schemas.android.com/apk/res/android">
        <manifest>
            <application>
                <activity android:name="com.facebook.FacebookActivity" 
                          android:theme="@android:style/Theme.Translucent.NoTitleBar" 
                          android:label="YourAppName" 
                          android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation" />
                <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>

                <provider android:name="com.facebook.FacebookContentProvider"
                          android:authorities="com.facebook.app.FacebookContentProvider<YOUR_APP_ID>"
                          android:exported="true" />
            </application>
        </manifest>
    </android>
<ti:app>

Add the Facebook App ID to Android Resources

Add a string element to the /platform/android/res/values/strings.xml file with the name attribute set to facebook_app_id and the node text set to your Facebook App ID. Create the file if it does not exist.

<resources>
    <string name="facebook_app_id">FACEBOOK_APP_ID</string>
</resources>

Generate the Key Hashes

Facebook requires you to add the Key Hash of the Android app in order for you to use the module. Steps to get the Key Hash as follows. Alternatively, if you do not have the correct Key Hash on the Android App, the App will give an error message when you login with the Key Hash of the App which you can then copy.

Use the following command to generate and receive the key-hashpath of your app. To do do, replace <sdk-version> with your SDK-version and run:

keytool -exportcert -alias androiddebugkey -keystore ~/Library/Application\ Support/Titanium/mobilesdk/osx/<sdk-version>/dev_keystore | openssl sha1 -binary | openssl base64

You would also require, to fill up the Google Play Package Name which is the Application ID and the Class Name which is the Application ID followed by the Application Name concatenated with the word Activity. Example, an App called Kitchensink with Application ID of "com.appcelerator.kitchensink" will have the Class Name as "com.appcelerator.kitchensink.KitchensinkActivity". Alternatively, you can check the Class Name in <project>/build/android/AndroidManifest.xml which is generated when you build the project. The launcher activity is the Class Name of the Application.

For more info, please see https://developers.facebook.com/docs/android/getting-started

Create a Facebook Proxy

Use the createActivityWorker() method to create a Facebook proxy. Pass the method a dictionary with the lifecycleContainer property set to the current active instance of a standalone Window (window not contained in a tab group) or TabGroup. Create the proxy before calling the open() method on either the window or tab group.

The Facebook module needs to hook into the lifecycle events of the current active activity in order to synchronize its state between various activities in the application, for example, to update the label of the Login button when the user logs in or out of Facebook.

Attach the proxy to the Window or TabGroup object, so it does not get garbage collected.

win.fbProxy = fb.createActivityWorker({ lifecycleContainer: win });

Module API Usage

Facebook Login and Authorization

To use Facebook, a user must logged into Facebook and explicitly authorize the application to perform certain actions, such as accessing profile information or posting status messages.

Call authorize to prompt the user to login and authorize the application. Before calling this method, set the Modules.Facebook.permissions property if additional permissions are needed.

Which approach you take depends on your UI and how central Facebook is to your application.

Manage Read and Write Permissions

In order to read or write content to a user's Facebook page, you need to request permission from the user. You can either request permissions when the user authorizes your application or request permissions on the fly.

Before the user logs in and authorizes the application, you can request permissions for the application to use by either: Setting the Modules.Facebook.permissions property if you are using authorize() method to have the user login and authorize the application.

For a complete list of permissions, see the official Facebook Permissions Reference

Refresh Application Permissions

Since the user can selectively turn application permissions on and off from their Facebook page, the application may need to refresh its granted permissions.

To refresh the application's permissions, call the refreshPermissionsFromServer() method, then listen for the Modules.Facebook.tokenUpdated event to be notified when permissions are updated.

fb.addEventListener('tokenUpdated', function (e) {
    Ti.API.info('Updated permissions: ' + JSON.stringify(fb.permissions));
});
fb.refreshPermissionsFromServer();

Share Dialogs

The Share dialog prompts a person to publish an individual story or an Open Graph story to their timeline. This does not require the user to authorize your app or any extended permissions, so it is the easiest way to enable sharing.

Pass either method parameters you want to add to the post, such as a link or hashtag, or to share the user's status, do not pass any parameters to the methods. Note: The link parameter is required by the Facebook SDK.

To monitor if the share request succeeded or not, listen to the Modules.Facebook.shareCompleted event.

fb.addEventListener('shareCompleted', function (e) {
    if (e.success) {
        Ti.API.info('Share request succeeded.');
    } else {
        Ti.API.warn('Failed to share.');
    }
});

fb.presentShareDialog({
    link: 'https://appcelerator.com/',
    hashtag: 'codestrong'
});

For details on the Share dialog, see the official Facebook Share Dialogs documentation.

Messenger Button

The Messenger button provides a quick mechanism for users to share content to the Facebook Messenger. A click on the button can share the content to multiple users.

To create a Messenger button, call the createMessengerButton() method and pass the "mode" and "style" properties:

var messengerButton = fb.createMessengerButton({
    mode: fb.MESSENGER_BUTTON_MODE_RECTANGULAR
    style: fb.MESSENGER_BUTTON_STYLE_BLUE
});
win.add(messengerButton);

For more information, see the MessengerButton API reference.

Login Tracking

The top-level loginTracking property and the LOGIN_TRACKING_ENABLED / LOGIN_TRACKING_LIMITED constants are supported on both iOS and Android. When set to LOGIN_TRACKING_LIMITED, calling authorize (or requestNewReadPermissions) starts Facebook's OIDC-based Limited Login flow: the SDK returns an Authentication Token (a JWT) instead of a classic Graph access token. The JWT is delivered as event.authenticationToken.tokenString on the login event — verify its signature server-side against Facebook's JWKS.

The LoginButton widget honors loginTracking on iOS only. The Android FB SDK's button does not expose Limited Login configuration, so on Android you must trigger Limited Login through Modules.Facebook.authorize() rather than via the button.

For more information, see the Login Tracking API reference and review the constants above.

Examples

Authorize

Shows official Facebook dialog for logging in the user and prompting the user to approve your requested permissions. Listen for the module's login event to determine whether the request succeeded.

var fb = require('facebook');
fb.initialize();
fb.addEventListener('login', function (e) {
    if (e.success) {
        alert('Logged in with User ID: ' + e.uid + ', Name: ' + JSON.parse(e.data).name);
        label.text = 'Logged In = ' + fb.loggedIn;
    }
    else if (e.cancelled) {
        // user cancelled
        alert('cancelled');
    }
    else {
        alert(e.error);
    }
});
fb.authorize();

Logout

Logout the user and forget the authorization token. The logout event is fired after the user is logged out.

fb.addEventListener('logout', function (e) {
    alert('Logged out');
});
fb.logout();

Authorize/Logout Using the Facebook LoginButton

You can use the the native Facebook LoginButton to allow the user to log in as required. The button updates its state automatically depending on whether the user is logged in or not. When the user is logged in, then the button will show "Logout", and vice-versa.

Note that you don't need to set a click listener or anything else on the button. To be notified when the user logs in or out, add event listeners for the login and logout events provided by the Facebook module, as in the example below.

// Don't forget to set your requested permissions, else the login button won't be effective.
var win = Ti.UI.createWindow({ backgroundColor: 'white' });
var fb = require('facebook');

fb.addEventListener('login', function (e) {
    if (e.success) {
        alert('Logged in');
    }
});
fb.addEventListener('logout', function (e) {
    alert('Logged out');
});

if (Ti.Platform.name === 'android') {
    win.fbProxy = fb.createActivityWorker({ lifecycleContainer: win });
}

// Add the button.  Note that it doesn't need a click event listener.
win.add(fb.createLoginButton({
        readPermissions: ['read_stream','email'],
        top: 50
}));

win.open()

Simple Graph API Call

This example makes a call to the "me" graph path, which represents the current user. The JSON results are simply displayed in an alert. This example assumes the user is already logged in. You can check this with <Modules.Facebook.loggedIn>.

fb.requestWithGraphPath('me', {}, 'GET', function (e) {
    if (e.success) {
        alert(e.result);
    } else if (e.error) {
        alert(e.error);
    } else {
        alert('Unknown response');
    }
});

Post a Photo Using the Graph API from the Gallery.

This example posts a photo to the user's account using the Graph API. This requires the "publish_actions" permission.

var b1 = Ti.UI.createButton({
    title: 'Upload Photo from Gallery with Graph API'
});

b1.addEventListener('click', function () {
    Titanium.Media.openPhotoGallery({
        success: function (event) {
            b1.title = 'Uploading Photo...';
            var data = { picture: event.media };
            // If publish_actions permission is not granted, request it
            if (fb.permissions.indexOf('publish_actions') === -1) {
                fb.requestNewPublishPermissions(['publish_actions'], fb.AUDIENCE_FRIENDS, function (e) {
                    if (!e.success) {
                        Ti.API.info('Publish permission error');
                        return;
                    }
                    if (e.cancelled) {
                        Ti.API.info('Publish permission cancelled');
                        return;
                    }
                    
                    Ti.API.info('Permissions: ' + fb.permissions);
                    fb.requestWithGraphPath('me/photos', data, 'POST', showRequestResult);
                });
            } else {
                fb.requestWithGraphPath('me/photos', data, 'POST', showRequestResult);
            }
        },
        error: function (e) {
            Ti.API.error('Error opening photo gallery: ' + e.error);
        }
    });
});

For more information on posting photos, see:

Post a Photo Using the Graph API with an image in resources directory

This example posts a photo to the user's account using the Graph API. This requires the "publish_actions" permission.

var b2 = Ti.UI.createButton({
    title: 'Upload Photo from file with Graph API',
    left: 10, 
    right: 10, 
    top: 90, 
    height: 80
});

b2.addEventListener('click', function () {
    b2.title = 'Uploading Photo...';
    var f = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory, 'images', 'flower.jpg');
    var blob = f.read();
    var data = {
        picture: blob
    };
    // If publish_actions permission is not granted, request it
    if (fb.permissions.indexOf('publish_actions') < 0) {
        fb.requestNewPublishPermissions(['publish_actions'], fb.AUDIENCE_FRIENDS, function (e) {
            if (e.success) {
                Ti.API.info('Permissions: ' + fb.permissions);
                fb.requestWithGraphPath('me/photos', data, 'POST', showRequestResult);
            }
            if (e.error) {
                Ti.API.info('Publish permission error');
            }
            if (e.cancelled) {
                Ti.API.info('Publish permission cancelled');
            }
        });
    } else {
        fb.requestWithGraphPath('me/photos', data, 'POST', showRequestResult);
    }
});

For more information on posting photos, see:

Show a basic Share Dialog

This example shows how to show a basic Share Dialog.

var button = Ti.UI.createButton({
    title: 'Share URL with Share Dialog'
});

button.addEventListener('click', function () {
    fb.presentShareDialog({
        link: 'https://appcelerator.com/',
        hashtag: 'codestrong'
    });
});

For more information on Facebook Dialogs, see:

Share content to the Facebook Messenger

This example shows how to share images, GIF's and videos to the Facebook messenger.

var btn = Ti.UI.createButton({
    title: 'Share media to messenger'
});
btn.addEventListener('click', function (e) {
    var media = [
        Ti.UI.createView({ height: 30, width: 30,backgroundColor: '#ff0' }).toImage(), // Image blob
        Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory, 'test.gif').read(), // GIF Blob
        Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory, 'movie.mp4').read() // Video Blob
    ];

    var options = Ti.UI.createOptionDialog({
        options: ['Photo', 'GIF', 'Video', 'Cancel'],
        cancel: 3
    });
    options.addEventListener('click', function (e) {
        if (e.index == 3) {
            return;
        }
        FB.shareMediaToMessenger({
            media: media[e.index],
            metadata: 'Ti rocks!',
            link: 'https://appcelerator.com',
        });
    });
    options.show();
});

For more information on sharing media to the Facebook Messenger, see:

Requesting additional permissions

This example shows how to use the requestNewPublishPermissions method to request additional permissions to publish a post to the user's wall.

fb.requestNewPublishPermissions(['publish_actions'], fb.AUDIENCE_FRIENDS, function (e) {
    if (e.success) {
        fb.requestWithGraphPath('me/feed', null, 'POST', showRequestResult);
    } else {
        Ti.API.debug('Failed authorization due to: ' + e.error);
    }
});

Properties 50

accessToken

Stringread-only

OAuth token set after a successful authorize.

advertiserTrackingEnabled

BooleaniPhoneiPadsince 16.0.0

Gets or sets the SDK's advertiser-tracking flag.

Maps to FBSDKSettings.sharedSettings.isAdvertiserTrackingEnabled.

Starting with the Facebook iOS SDK v18, a LOGIN_TRACKING_ENABLED (classic) login attempt is silently shimmed into the Limited Login flow whenever this flag is false (the SDK default until App Tracking Transparency has been granted). Set this to true after a successful ATTrackingManager.requestTrackingAuthorization in your app to keep classic login behaviour and continue receiving an Access Token rather than an Authentication Token.

See https://developers.facebook.com/docs/facebook-login/ios/limited-login/ for the difference between classic and Limited Login.

Default: false

appID

String

If not explicitly set, the default will be read from the application's plist (FacebookAppID) which is the recommended way.

Since Titanium SDK 6.2.0, this property also has a getter to return the currently set appID.

authenticationToken

StringAndroidsince 19.0.0read-only

Returns the raw Authentication Token (JWT) from the most recent Limited Login, or an empty string if none is currently set.

Equivalent to reading FBSDKAuthenticationToken.currentAuthenticationToken.tokenString on iOS and AuthenticationToken.getCurrentAuthenticationToken().getToken() on Android.

canPresentOpenGraphActionDialog

BooleanAndroidsince 4.0.0read-only

Checks if the device can support the use of the Facebook Open Graph action dialog from the Facebook App.

EVENT_NAME_ADDED_PAYMENT_INFO

Stringsince Android 8.0.0, iPhone 7.0.0, iPad 7.0.0read-only

Log this event when the user has entered their payment info.

EVENT_NAME_ADDED_TO_CART

Stringsince Android 8.0.0, iPhone 7.0.0, iPad 7.0.0read-only

Log this event when the user has added an item to their cart.

EVENT_NAME_INITIATED_CHECKOUT

Stringsince Android 8.0.0, iPhone 7.0.0, iPad 7.0.0read-only

Log this event when the user has entered the checkout process.

EVENT_NAME_VIEWED_CONTENT

Stringsince Android 8.0.0, iPhone 7.0.0, iPad 7.0.0read-only

Log this event when a user has viewed a form of content in the app.

EVENT_PARAM_CONTENT

Stringsince Android 8.0.0, iPhone 7.0.0, iPad 7.0.0read-only

Parameter key used to specify data for the one or more pieces of content being logged about.

EVENT_PARAM_CONTENT_ID

Stringsince Android 8.0.0, iPhone 7.0.0, iPad 7.0.0read-only

Parameter key used to specify an ID for the specific piece of content being logged about.

EVENT_PARAM_CONTENT_TYPE

Stringsince Android 8.0.0, iPhone 7.0.0, iPad 7.0.0read-only

Parameter key used to specify a generic content type/family for the logged event.

EVENT_PARAM_CURRENCY

Stringsince Android 8.0.0, iPhone 7.0.0, iPad 7.0.0read-only

Parameter key used to specify currency used with logged event.

EVENT_PARAM_NUM_ITEMS

Stringsince Android 8.0.0, iPhone 7.0.0, iPad 7.0.0read-only

Parameter key used to specify how many items are being processed.

loggedIn

Booleanread-only

Indicates if the user is logged in.

LOGIN_TRACKING_ENABLED

Numbersince 10.0.0read-only

Use with LoginButton.loginTracking (iOS) or the top-level loginTracking property to set the desired tracking preference.

For more information on the differences between LOGIN_TRACKING_ENABLED and LOGIN_TRACKING_LIMITED see: https://developers.facebook.com/docs/facebook-login/limited-login/

LOGIN_TRACKING_LIMITED

Numbersince 10.0.0read-only

Use with LoginButton.loginTracking (iOS) or the top-level loginTracking property to set the desired tracking preference.

For more information on the differences between LOGIN_TRACKING_ENABLED and LOGIN_TRACKING_LIMITED see: https://developers.facebook.com/docs/facebook-login/limited-login/

MESSENGER_BUTTON_MODE_CIRCULAR

NumberiPhoneiPadsince 5.4.0read-only

Use with MessengerButton.mode to specify the default send button reading "Send".

You can localize the button by localizing "Send" in your strings.xml. Learn more about that topic here.

nonce

StringAndroidsince 19.0.0

Optional nonce used by Limited Login (LOGIN_TRACKING_LIMITED) to bind the issued Authentication Token to a server-side challenge.

When set, the value is embedded as the nonce claim of the JWT the SDK returns. Validate the same value on your backend to defeat replay. If omitted, the Facebook SDK mints a random UUID. Has no effect when loginTracking == LOGIN_TRACKING_ENABLED.

permissions

Array<String>

Array of permissions to request for your app.

Be sure the permissions you want are set before calling authorize.

For a complete list of permissions, see the official Facebook Permissions Reference

iOS Platform Notes

On iOS, do not request any write permissions before calling the authorize() method. Use the requestNewPublishPermissions() to request write permissions once the user authorizes the application.

Prior to Release 4.0.0

To use the build-in iOS 6 login, this property cannot contain any of the following: offline_access, publish_actions, publish_stream, publish_checkins, ads_management, create_event, rsvp_event, manage_friendlists, manage_notifications, or manage_pages.

uid

Stringread-only

Unique user ID returned from Facebook.

Methods 17

Prompts the user to log in (if not already logged in) and authorize your application. You can also use LoginButton to log in.

Be sure to set your required permissions before calling authorize.

A login event is generated to indicate a successful or unsuccessful login attempt.

iOS Platform Notes

On iOS, do not request any write permissions before calling this method. Use the requestNewPublishPermissions() to request write permissions once the user authorizes the application.

createActivityWorker

Androidsince 4.0.0

Creates a Facebook proxy to hook into the activity of either a standalone Titanium.UI.Window (not inside a TabGroup) or Titanium.UI.TabGroup.

Set the lifecycleContainer property in the dictionary passed to the method to either the current active instance of a Titanium.UI.Window or Titanium.UI.TabGroup in order to monitor the activity's lifecycle events, required by Facebook to synchronize its state between various activities in the application.

The proxy object must be created before calling the open() method on the associated Window or TabGroup.

Parameters
ParametersTypeDescription
parametersDictionary<Titanium.Proxy>

Properties to set on a new object, including any defined by Titanium.Proxy except those marked not-creation or read-only.

Note: You must set the lifecycleContainer property.

initialize

since 4.0.0

Loads a cached Facebook session if available, then fires the login event.

Be sure to set your login and logout event listeners before calling initialize.

**Note: This method needs to be called before calling Modules.Facebook.authorize in order to be handle the auth-flow correctly. Otherwise, you might see a white screen without any response.

logCustomEvent

since 4.0.0

Logs a custom event to Facebook.

From the Facebook API Reference:

Events are not sent immediately when logged. They're cached and flushed out to the Facebook servers in a number of situations:

  • when an event count threshold is passed (currently 100 logged events).
  • when a time threshold is passed (currently 15 seconds).
  • when an app has gone to background and is then brought back to the foreground.

Some things to note when logging events:

  • There is a limit on the number of unique event names an app can use, on the order of 300.
  • Event names must be between 2 and 40 characters and must consist of alphanumeric characters, _, - or spaces.
Parameters
ParametersTypeDescription
eventString

Arbitrary string to log as an event.

valueToSum?Number

An arbitrary number that can represent any value (e.g., a price or a quantity). When reported, all of the valueToSum properties will be summed together in Facebook Analytics for Apps (since 5.4.0).

params?Object

A dictionary object containing optional parameters (since 5.4.0).

Clears the OAuth accessToken and logs out the user.

logPurchase

since 5.2.0

Log a purchase of the specified amount, in the specified currency.

Parameters
ParametersTypeDescription
amountNumber

Purchase amount to be logged, as expressed in the specified currency. This value will be rounded to the thousandths place (e.g., 12.34567 becomes 12.346).

currencyString

Currency, is denoted as, e.g. "USD", "EUR", "GBP". See ISO-4217 for specific values.

parameters?Object

A dictionary object containing optional parameters (since 8.0.0 in android and since 7.0.0 in ios).

Log an app event that tracks that the application was open via Push Notification.

Parameters
ParametersTypeDescription
payloadDictionary

Notification payload received via in the push-notification callback.

action?String

Name of the action that was taken.

Opens a Facebook photo share dialog.

Note: The images parameter is required by the Facebook SDK.

Android Note: In order to share images on Android, the Facebook app needs to be installed and the "content provider" settings in your Android manifest needs to be configured:

<provider android:name="com.facebook.FacebookContentProvider"
          android:authorities="com.facebook.app.FacebookContentProvider<YOUR_APP_ID>"
          android:exported="true" />

Listen for the Modules.Facebook.shareCompleted to be notified if the attempt was successful or not.

Parameters
ParametersTypeDescription
paramsSharePhotoContentParams

A dictionary object containing the required and optional parameters.

2 fields
mode? Number

The mode to select for presenting a share dialog.

photos Array<SharePhotoContentPhotoParams>

An array of photos that is represented by an object of photo, caption and userGenerated parameters.

Opens a Facebook link share dialog.

Note: The link parameter is required by the Facebook SDK.

Listen for the Modules.Facebook.shareCompleted to be notified if the attempt was successful or not.

Parameters
ParametersTypeDescription
paramsShareLinkContentParams

A dictionary object containing the required and optional parameters.

6 fields
hashtag String

Hashtag for the content being shared.

link String

URL to share (required for any link of sharing).

mode? Number

The mode to select for presenting a share dialog. Only used in presentShareDialog.

placeID String

The ID for a place to tag with this content.

referal String

A value to be added to the referrer URL when a person follows a link from this shared content on feed.

to Array<String>

List of IDs for taggable people to tag with this content.

Makes a request to Facebook to get the latest permissions granted.

Facebook now grants total control over granted permissions, and if the user modified the permissions outside of your app your cached token may not be updated.

Listen for the Modules.Facebook.tokenUpdated event to be notified if the attempt was successful.

requestNewPublishPermissions

deprecatedsince 4.0.0

Deprecated since 8.2.0

Request all permissions via the permissions property before calling authorize.

Makes a request to Facebook for additional write permissions.

Note that it is not an error for the user to 'Skip' your requested permissions, so you should check the module's permissions property following the call.

Parameters
ParametersTypeDescription
permissionsArray<String>

Array of additional permissions to request. For a complete list of permissions, see the official Facebook Permissions Reference

audienceNumber

The extent of the visibility write permissions will have.

callbackCallback<FacebookPermissionResponse>

Callback to invoke when the request completes.

3 fields
cancelled Boolean

Indicates if the user canceled the dialog.

error String

Error message, if any returned. Will be undefined if success is true.

success Boolean

Indicates if successful

requestNewReadPermissions

deprecatedsince 4.0.0

Deprecated since 8.2.0

Request all permissions via the permissions property before calling authorize.

Makes a request to Facebook for additional read permissions.

Note that it is not an error for the user to 'Skip' your requested permissions, so you should check the module's permissions property following the call.

Parameters
ParametersTypeDescription
permissionsArray<String>

Array of additional permissions to request. For a complete list of permissions, see the official Facebook Permissions Reference

callbackCallback<FacebookPermissionResponse>

Callback to invoke when the request completes.

3 fields
cancelled Boolean

Indicates if the user canceled the dialog.

error String

Error message, if any returned. Will be undefined if success is true.

success Boolean

Indicates if successful

Makes a Facebook Graph API request.

If the request requires user authorization, the user must be logged in, and your app must be authorized to make the request. You can check the loggedIn property to determine if the user is logged in.

Every Facebook object has an associated path. For example, "me" requests information about the current user.

For a complete list of Graph API methods, parameters and return types, see the official Facebook Graph API documentation.

Parameters
ParametersTypeDescription
pathString

Graph API path to request.

paramsDictionary

A dictionary object for setting parameters required by the call, if any.

httpMethodString

The HTTP method (GET/POST/DELETE) to use for the call.

callbackCallback<FacebookGraphResponse>

Callback to invoke when the request completes.

2 fields
path String

Graph API path of the original request.

result String

If successful, returns the JSON response returned by Facebook. If the request is not successfully completed, the result is undefined.

setCurrentAccessToken

iPhoneiPadsince 6.2.0

Set a new access token for using Facebook services.

Parameters
ParametersTypeDescription
paramsCurrentAccessTokenParams

A dictionary object containing required and optional parameters.

Note: There is an open issue in the native Facebook SDK causing the appID from not being updated although specified in the parameters. You can use the Modules.Facebook.appID setter to change the appID inside your app.

7 fields
accessToken String

The opaque token string.

appID String

The app ID.

declinedPermissions Array<String>

The declined permissions.

exipirationDate Date

The optional expiration date (defaults to distant future).

permissions Array<String>

The granted permissions.

refreshDate Date

The optional date the token was last refreshed (defaults to today).

userID String

The user ID.

Sets a device token to register the current application installation for push notifications.

Parameters
ParametersTypeDescription
deviceTokenString

Device-token received when registering for push-notifications.

Events 6

inviteCompleted

since 5.4.0

Fired when the Invite dialog is closed.

Event properties
Event propertiesTypeDescription
successBoolean

Returns true if request succeeded, false otherwise.

cancelledNumber

Indicates if the user canceled the request by closing the dialog.

errorString

Error message, if any returned. Will be undefined if success is true.

Fired at session login.

Event properties
Event propertiesTypeDescription
successBoolean

Indicates if the user was logged in successfully. Returns true if request succeeded, false otherwise.

cancelledNumber

Indicates if the user canceled the login request by closing the dialog.

errorString

Error message, if any returned. Will be undefined if success is true.

codeNumber

Error code. Error code will be 0 if success is true, nonzero otherwise. If the error was generated by the operating system, that system's error value is used. Otherwise, this value will be -1.

uidString

User ID returned by Facebook if the login was successful.

dataString

Data returned by Facebook when we query for the UID (using graph path "me") after a successful login. Data is in JSON format, and includes information such as user name, locale and gender.

For Limited Login (loginTracking == LOGIN_TRACKING_LIMITED) no Graph request is made — instead this contains a JSON object built from the verified claims of the Authentication Token (id, name, firstName, middleName, lastName, email, picture).

authenticationTokenDictionary<LimitedLoginAuthenticationToken>

OIDC Authentication Token returned by the Facebook SDK when the login attempt was made with loginTracking == LOGIN_TRACKING_LIMITED.

The tokenString is a signed JWT — forward it to your backend and verify its signature against Facebook's JWKS (https://www.facebook.com/.well-known/oauth/openid/jwks) with aud pinned to your Facebook App ID and iss pinned to https://www.facebook.com. Limited Login does not issue an Access Token, so the JWT and its claims are the only authoritative identity material available to the server.

Undefined when classic login (LOGIN_TRACKING_ENABLED) was used.

3 fields
graphDomain? String

Optional graph domain hint returned by the iOS SDK (e.g. gaming). undefined on Android.

nonce String

The nonce echoed back by Facebook. Matches the nonce you supplied (Android) or the value the SDK generated, and is also present as a claim inside the JWT.

tokenString String

The signed JWT (header.payload.signature) issued by Facebook. Verify on your backend.

Fired at session logout.

Fired when the Send Request dialog is closed.

Event properties
Event propertiesTypeDescription
successBoolean

Returns true if request succeeded, false otherwise.

cancelledNumber

Indicates if the user canceled the request by closing the dialog.

errorString

Error message, if any returned. Will be undefined if success is true.

dataDictionary

data returned by Facebook. See Facebook reference for details.

shareCompleted

since 4.0.0

Fired when the Share dialog or Web Share dialog is closed.

Event properties
Event propertiesTypeDescription
successBoolean

Returns true if request succeeded, false otherwise.

cancelledNumber

Indicates if the user canceled the request by closing the dialog.

errorString

Error message, if any returned. Will be undefined if success is true.

Modules.Facebook.LoginButton

viewAndroidiPhoneiPadsince 3.1.0

Extends Titanium.UI.View

A Facebook Login Button.

Use the createLoginButton() method to create a Login button. If you want to request user permissions when the user logs in, set either the Modules.Facebook.LoginButton.readPermissions or Modules.Facebook.LoginButton.publishPermissions property, but do not set both. If both properties are set, the application will throw an exception. If neither property is set, by default, only the user_profile permission is requested.

The Login button does not require a click event handler or any listeners. Click events on the button are automatically handled by the Facebook module.

The button changes its label to reflect the current state of the Facebook session. For example, if the user is already logged in, the button will show "Logout".

Android Platform Notes

In Android, the button's width will change depending on the current state it is in. When logged out, it will show "Log in with Facebook" and its width will match the length of the text. When logged in, it will show "Log out" and its width will match the length of the text.

iOS Platform Notes

In iOS, the width and height of the button can be changed using the width and height property. The Facebook SDK 4.19.0 and later (used in Ti.Facebook 5.4.0 and later) provides an updated Login button. The title now is "Continue with Facebook" instead of "Login with Facebook" and the recommended height is 28px. Please always specify a height for best results.

Properties 7

nonce

StringiPhoneiPadsince 10.0.0

Gets or sets an optional nonce to use for login attempts.

A valid nonce must be a non-empty string without whitespace. An invalid nonce will not be set. Instead, default unique nonceswill be used for login attempts.

publishPermissions

Array<String>since 4.0.0

Requested write permissions.

For a complete list of permissions, see the official Facebook Permissions Reference.

Sets the permissions to use when the session is opened. The permissions here should only be write permissions. If any read permissions are included, the login attempt by the user will fail. The LoginButton can only be associated with either read permissions or publish permissions, but not both. Using both the readPermissions and publishPermissions property on the same instance of LoginButton will result in an exception being thrown.

Set this property before the session is open. If this property is set after the session is opened, and the list of permissions passed in is not a subset of the permissions granted during the authorization, it will log an error.

Since the session can be automatically opened when the LoginButton is constructed, it is important to always pass in a consistent set of permissions to this property, or manage the setting of permissions outside of the LoginButton class altogether (by managing the session explicitly).

readPermissions

Array<String>since 4.0.0

Requested read permissions.

For a complete list of permissions, see the official Facebook Permissions Reference.

Sets the permissions to use when the session is opened. The permissions here can only be read permissions. If any publish permissions are included, the login attempt by the user will fail. The LoginButton can only be associated with either read permissions or publish permissions, but not both. Using both the readPermissions and publishPermissions property on the same instance of LoginButton will result in an exception being thrown.

Set this property before the session is open. If this property is set after the session is opened, and the list of permissions passed in is not a subset of the permissions granted during the authorization, it will log an error.

Since the session can be automatically opened when the LoginButton is constructed, it is important to always pass in a consistent set of permissions to this property, or manage the setting of permissions outside of the LoginButton class altogether (by managing the session explicitly).

RequestDialogParams

pseudoAndroidiPhoneiPadsince 4.0.0

Parameters to pass to presentSendRequestDialog() method.

Properties 8

message

String

Message to send with the request.

objectID

Stringsince 5.0.0

The Open Graph object ID of the object being sent. Required if actionType is set.

recipients

Array<String>since 5.0.0

Array of pre-selected facebook ids.

recipientSuggestions

Array<String>since 5.0.0

An array of user IDs that will be included in the dialog as the first suggested friends. Cannot be used together with filters.

title

String

Title of request.

ShareToMessengerParams

pseudoiPhoneiPadsince 5.4.0

Parameters to pass to shareMediaToMessenger() method.

Properties 4

Media to send with the messenger. Allowed media are images, GIF's and videos represented as Blobs.

metadata

String

Pass additional information to be sent to Messenger which is sent back to the user's app when they reply to an attributed message.

Optional property describing whether the content should be rendered like a sticker.

Setting this property informs Messenger that the media content should be rendered as a sticker. This option is only used for static images.

Default: false