### Example App Lifecycle Commands Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/README.md Commands to manage the development and execution of the example application. ```bash yarn example:start ``` ```bash yarn example:ios ``` ```bash yarn example:android ``` ```bash yarn example:devcopy ``` ```bash refresh-example.sh ``` -------------------------------- ### Install iOS dependencies with CocoaPods Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/README.md After installing the library, navigate to the ios directory and run pod install to link native dependencies. ```bash $ cd ios/ && pod install ``` -------------------------------- ### Install Dependencies Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/CONTRIBUTING.md Install project dependencies using Yarn after cloning the repository. ```bash yarn ``` -------------------------------- ### Install react-native-fbsdk-next using npm Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/README.md Use this command to add the library to your project dependencies with npm. ```bash npm install --save react-native-fbsdk-next ``` -------------------------------- ### Install react-native-fbsdk-next using Yarn Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/README.md Use this command to add the library to your project dependencies with Yarn. ```bash yarn add react-native-fbsdk-next ``` -------------------------------- ### Graph API Request Example Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/README.md Demonstrates how to create and execute a Graph API request to fetch user information. Includes a callback to handle the response or errors. ```javascript // ... import { GraphRequest, GraphRequestManager } from 'react-native-fbsdk-next'; // ... // Create response callback. _responseInfoCallback(error, result) { if (error) { console.log("Error fetching data: " + error.toString()); } else { console.log("Success fetching data: " + result.toString()); } } // Create a graph request asking for user information with a callback to handle the response. const infoRequest = new GraphRequest( "/me", null, this._responseInfoCallback, ); // Start the graph request. new GraphRequestManager().addRequest(infoRequest).start(); ``` -------------------------------- ### Fetch Deferred App Links Source: https://context7.com/thebergamo/react-native-fbsdk-next/llms.txt Retrieves the original link that led to an app install for attribution tracking. Call this function during app startup. ```javascript import { AppLink } from 'react-native-fbsdk-next'; // Fetch deferred app link (for tracking install attribution) async function handleDeferredAppLink() { try { const url = await AppLink.fetchDeferredAppLink(); if (url) { console.log('Deferred app link:', url); // Navigate to the appropriate content based on the URL handleDeepLink(url); } else { console.log('No deferred app link found'); } } catch (error) { console.log('Error fetching deferred app link:', error); } } function handleDeepLink(url) { // Parse and handle the deep link URL const urlObj = new URL(url); const path = urlObj.pathname; const params = Object.fromEntries(urlObj.searchParams); console.log('Deep link path:', path); console.log('Deep link params:', params); // Navigate based on the link content // navigation.navigate(path, params); } // Call on app startup handleDeferredAppLink(); ``` -------------------------------- ### Jest Mock Configuration Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/README.md Configures the library mock in the Jest setup file to enable testing. ```javascript jest.mock("react-native-fbsdk-next", () => require("react-native-fbsdk-next/jest/mocks").default); ``` -------------------------------- ### Expo Plugin with API Configuration Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/README.md Example of configuring the react-native-fbsdk-next plugin with required and optional API properties in app.json or app.config.js. Rebuild your app after changes. ```json { "expo": { "plugins": [ [ "react-native-fbsdk-next", { "appID": "48127127xxxxxxxx", "clientToken": "c5078631e4065b60d7544a95xxxxxxxx", "displayName": "RN SDK Demo", "scheme": "fb48127127xxxxxxxx", "advertiserIDCollectionEnabled": false, "autoLogAppEventsEnabled": false, "isAutoInitEnabled": true, "iosUserTrackingPermission": "This identifier will be used to deliver personalized ads to you." } ] ] } } ``` -------------------------------- ### Initialize SDK Settings Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/README.md Initialize the Facebook SDK with your app's details and enable auto app events. This setup is crucial for accurate event tracking and user data collection. ```javascript Settings.setAppID($appId); Settings.setAppName($appName); Settings.setGraphAPIVersion($version); Settings.setAutoLogAppEventsEnabled($autoLogAppEvents); Settings.initializeSDK() ``` -------------------------------- ### Handle URL Opening for Facebook SDK in AppDelegate.m Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/README.md Implement this method in your `/ios/PROJECT/AppDelegate.m` file to handle URL opening for the Facebook SDK, especially when Facebook app is installed. This is for React Native versions 0.76 and below. ```objective-c - (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary *)options { return [[FBSDKApplicationDelegate sharedInstance]application:app openURL:url options:options]; } ``` -------------------------------- ### Enable Auto App Installs and Tracking Permissions in Expo Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/README.md To enable auto app installs and handle user consent for data collection on iOS, configure your app.json and implement tracking permission requests. This ensures compliance with privacy regulations and proper event logging. ```javascript import { requestTrackingPermissionsAsync } from 'expo-tracking-transparency'; const { status } = await requestTrackingPermissionsAsync(); Settings.initializeSDK(); if (status === 'granted') { await Settings.setAdvertiserTrackingEnabled(true); } ``` -------------------------------- ### Get Access Token Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/README.md Retrieve the current access token for the logged-in user. This token is required for making API calls on behalf of the user. ```javascript AccessToken.accessToken ``` -------------------------------- ### Podfile Workaround for Swift/Objective-C Mixing Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/README.md This Ruby script modifies the build settings for native targets within a CocoaPods installation to resolve potential conflicts when mixing Swift and Objective-C code, particularly relevant for older versions of the Facebook SDK. ```ruby installer.aggregate_targets.first.user_project.native_targets.each do |target| target.build_configurations.each do |config| config.build_settings['LIBRARY_SEARCH_PATHS'] = ['$(inherited)', '$(SDKROOT)/usr/lib/swift'] end end ``` -------------------------------- ### Get Current Profile Information Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/README.md Retrieve the current user's profile information after a successful login. The data returned depends on granted permissions and platform limitations (e.g., email on Android). ```javascript // ... import { Profile } from "react-native-fbsdk-next"; // ... const currentProfile = Profile.getCurrentProfile().then( function(currentProfile) { if (currentProfile) { console.log( "The current logged user is: " + currentProfile.name + ". Their profile id is: " + currentProfile.userID ); } } ); ``` -------------------------------- ### Get Attribution ID Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/README.md Retrieve the attribution ID, which can be used to understand the source of app installs or user engagement. ```javascript AppEventsLogger.getAttributionID() ``` -------------------------------- ### Initialize Facebook SDK in didFinishLaunchingWithOptions Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/README.md Initializes the Facebook SDK and requests App Tracking Transparency authorization for iOS 14+ within the application launch lifecycle. ```swift public override func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil ) -> Bool { // ... your existing code ... // Initialize Facebook SDK ApplicationDelegate.shared.application( application, didFinishLaunchingWithOptions: launchOptions ) // Request App Tracking Transparency authorization (iOS 14+) if #available(iOS 14, *) { ATTrackingManager.requestTrackingAuthorization { _ in AppEvents.shared.activateApp() } } else { AppEvents.shared.activateApp() } // ... rest of your code ... return super.application(application, didFinishLaunchingWithOptions: launchOptions) } ``` -------------------------------- ### Initialize Facebook SDK in AppDelegate.m Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/README.md Add this line within the `didFinishLaunchingWithOptions` method in your `/ios/PROJECT/AppDelegate.m` file for React Native versions 0.76 and below. ```objective-c [[FBSDKApplicationDelegate sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions]; ``` -------------------------------- ### Initialize SDK in Expo Source: https://context7.com/thebergamo/react-native-fbsdk-next/llms.txt Request tracking permissions and initialize the SDK within an Expo application. ```javascript // App.tsx - Initialize SDK with tracking transparency (Expo) import { useEffect } from 'react'; import { requestTrackingPermissionsAsync } from 'expo-tracking-transparency'; import { Settings } from 'react-native-fbsdk-next'; function App() { useEffect(() => { async function initializeFacebookSDK() { // Request tracking permission on iOS const { status } = await requestTrackingPermissionsAsync(); // Initialize SDK Settings.initializeSDK(); // Enable advertiser tracking if permission granted if (status === 'granted') { await Settings.setAdvertiserTrackingEnabled(true); } } initializeFacebookSDK(); }, []); return ( // Your app content ); } export default App; ``` -------------------------------- ### Get User ID Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/README.md Retrieve the currently set user ID. This is useful for associating events with specific logged-in users. ```javascript AppEventsLogger.getUserId() ``` -------------------------------- ### Flush App Events Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/README.md Manually flush any queued app events. This can be useful for ensuring events are sent immediately, for example, before the app is closed. ```javascript AppEventsLogger.flush() ``` -------------------------------- ### Settings - SDK Initialization and Configuration Source: https://context7.com/thebergamo/react-native-fbsdk-next/llms.txt The Settings module provides methods for initializing the Facebook SDK and configuring various SDK behaviors including app ID, client token, and privacy-related settings like advertiser tracking. ```APIDOC ## Settings - SDK Initialization and Configuration ### Description The Settings module provides methods for initializing the Facebook SDK and configuring various SDK behaviors including app ID, client token, and privacy-related settings like advertiser tracking. ### Methods #### `Settings.initializeSDK()` - **Description**: Initializes the Facebook SDK. Required for iOS, optional for Android. - **Method**: `CALL` #### `Settings.setAppID(appID: string)` - **Description**: Sets the Facebook App ID. Useful for multi-app scenarios. - **Method**: `CALL` - **Parameters**: - **appID** (string) - Required - The Facebook App ID. #### `Settings.setClientToken(clientToken: string)` - **Description**: Sets the client token for authentication. - **Method**: `CALL` - **Parameters**: - **clientToken** (string) - Required - The client token. #### `Settings.setAppName(appName: string)` - **Description**: Sets the Facebook App name. - **Method**: `CALL` - **Parameters**: - **appName** (string) - Required - The name of the Facebook App. #### `Settings.setGraphAPIVersion(version: string)` - **Description**: Sets the Graph API version to use. - **Method**: `CALL` - **Parameters**: - **version** (string) - Required - The Graph API version (e.g., 'v18.0'). #### `Settings.setAutoLogAppEventsEnabled(enabled: boolean)` - **Description**: Configures whether to automatically log app events. - **Method**: `CALL` - **Parameters**: - **enabled** (boolean) - Required - `true` to enable auto-logging, `false` to disable. #### `Settings.setAdvertiserIDCollectionEnabled(enabled: boolean)` - **Description**: Enables or disables the collection of the advertiser ID. - **Method**: `CALL` - **Parameters**: - **enabled** (boolean) - Required - `true` to enable collection, `false` to disable. #### `Settings.setAdvertiserTrackingEnabled(enabled: boolean)` - **Description**: Sets the advertiser tracking enabled status (iOS 14+ only). - **Method**: `CALL` - **Parameters**: - **enabled** (boolean) - Required - `true` to enable tracking, `false` to disable. - **Returns**: A Promise that resolves with a boolean indicating success. #### `Settings.getAdvertiserTrackingEnabled()` - **Description**: Gets the current advertiser tracking status (iOS only). - **Method**: `CALL` - **Returns**: A Promise that resolves with a boolean indicating if tracking is enabled. #### `Settings.setDataProcessingOptions(options: string[], country?: number, state?: number)` - **Description**: Sets data processing options for GDPR/CCPA compliance. - **Method**: `CALL` - **Parameters**: - **options** (string[]) - Required - An array of options. Use `['LDU']` to enable Limited Data Use. An empty array means no restrictions. - **country** (number) - Optional - A numerical representation of the country (e.g., 1 for US). - **state** (number) - Optional - A numerical representation of the state (e.g., 1000 for California). ### Request Example ```javascript import { Settings } from 'react-native-fbsdk-next'; // Initialize the SDK Settings.initializeSDK(); // Set Facebook App ID Settings.setAppID('YOUR_APP_ID'); // Set client token Settings.setClientToken('YOUR_CLIENT_TOKEN'); // Set app display name Settings.setAppName('My Facebook App'); // Set Graph API version Settings.setGraphAPIVersion('v18.0'); // Configure auto-logging of app events Settings.setAutoLogAppEventsEnabled(true); // Enable/disable advertiser ID collection Settings.setAdvertiserIDCollectionEnabled(true); // iOS only: Set advertiser tracking enabled Settings.setAdvertiserTrackingEnabled(true).then((success) => { console.log('Advertiser tracking set:', success); }); // iOS only: Get current advertiser tracking status Settings.getAdvertiserTrackingEnabled().then((enabled) => { console.log('Advertiser tracking enabled:', enabled); }); // Set data processing options Settings.setDataProcessingOptions(['LDU'], 1, 1000); ``` ``` -------------------------------- ### Initialize Facebook SDK in Expo AppDelegate Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/README.md Implement `application(_:didFinishLaunchingWithOptions:)` in your `AppDelegate` to initialize the Facebook SDK and handle app tracking authorization for iOS 14+. ```swift import Expo import React import FBSDKCoreKit import AppTrackingTransparency @UIApplicationMain public class AppDelegate: ExpoAppDelegate { public override func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil ) -> Bool { // Your existing Expo setup code... // Initialize Facebook SDK ApplicationDelegate.shared.application( application, didFinishLaunchingWithOptions: launchOptions ) // Request tracking authorization if #available(iOS 14, *) { ATTrackingManager.requestTrackingAuthorization { _ in AppEvents.shared.activateApp() } } else { AppEvents.shared.activateApp() } return super.application(application, didFinishLaunchingWithOptions: launchOptions) } // CRITICAL: Required for Facebook SSO to work public override func application( _ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:] ) -> Bool { let handledByFB = ApplicationDelegate.shared.application( app, open: url, options: options) let handledByRN = RCTLinkingManager.application( app, open: url, options: options) let handledBySuper = super.application( app, open: url, options: options) return handledByFB || handledByRN || handledBySuper } // Optional: Activate app when it becomes active open override func applicationDidBecomeActive(_ application: UIApplication) { super.applicationDidBecomeActive(application) AppEvents.shared.activateApp() } } ``` -------------------------------- ### Initialize Facebook SDK Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/README.md Manually trigger SDK initialization from JavaScript, useful for handling GDPR consent flows. ```javascript import { Settings } from 'react-native-fbsdk-next'; // Ask for consent first if necessary // Possibly only do this for iOS if no need to handle a GDPR-type flow Settings.initializeSDK(); ``` -------------------------------- ### Configure Facebook SDK Settings Source: https://context7.com/thebergamo/react-native-fbsdk-next/llms.txt Use the Settings module to initialize the SDK and configure app-specific parameters, privacy settings, and event logging behavior. ```javascript import { Settings } from 'react-native-fbsdk-next'; // Initialize the SDK (required for iOS, optional for Android) Settings.initializeSDK(); // Set Facebook App ID (useful for multi-app scenarios) Settings.setAppID('YOUR_APP_ID'); // Set client token for authentication Settings.setClientToken('YOUR_CLIENT_TOKEN'); // Set app display name Settings.setAppName('My Facebook App'); // Set Graph API version Settings.setGraphAPIVersion('v18.0'); // Configure auto-logging of app events Settings.setAutoLogAppEventsEnabled(true); // Enable/disable advertiser ID collection Settings.setAdvertiserIDCollectionEnabled(true); // iOS only: Set advertiser tracking enabled (iOS 14+) Settings.setAdvertiserTrackingEnabled(true).then((success) => { console.log('Advertiser tracking set:', success); }); // iOS only: Get current advertiser tracking status Settings.getAdvertiserTrackingEnabled().then((enabled) => { console.log('Advertiser tracking enabled:', enabled); }); // Set data processing options for GDPR/CCPA compliance // Empty array means no restrictions, ['LDU'] enables Limited Data Use Settings.setDataProcessingOptions(['LDU'], 1, 1000); // country=1 (US), state=1000 (California) ``` -------------------------------- ### Get Anonymous ID Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/README.md Retrieve the anonymous ID used for event tracking. This ID helps in identifying unique users without relying on personal information. ```javascript AppEventsLogger.getAnonymousID() ``` -------------------------------- ### Get Current Access Token Source: https://context7.com/thebergamo/react-native-fbsdk-next/llms.txt Retrieves the current Facebook access token and associated user information. Useful for checking login status and validating token details. ```javascript import { AccessToken } from 'react-native-fbsdk-next'; // Get the current access token async function checkLoginStatus() { const accessToken = await AccessToken.getCurrentAccessToken(); if (accessToken) { console.log('User is logged in'); console.log('Access token:', accessToken.accessToken); console.log('User ID:', accessToken.userID); console.log('App ID:', accessToken.applicationID); console.log('Permissions:', accessToken.permissions); console.log('Declined permissions:', accessToken.declinedPermissions); console.log('Expired permissions:', accessToken.expiredPermissions); console.log('Expires at:', new Date(accessToken.expirationTime)); console.log('Last refresh:', new Date(accessToken.lastRefreshTime)); console.log('Data access expires:', new Date(accessToken.dataAccessExpirationTime)); // Check if token is expired const isExpired = accessToken.expirationTime < Date.now(); return !isExpired; } return false; } ``` -------------------------------- ### Configure Expo Plugin Source: https://context7.com/thebergamo/react-native-fbsdk-next/llms.txt Define SDK settings within the Expo configuration file to initialize the Facebook SDK. ```json { "expo": { "plugins": [ [ "react-native-fbsdk-next", { "appID": "1234567890", "clientToken": "abcdef123456", "displayName": "My App", "scheme": "fb1234567890", "advertiserIDCollectionEnabled": false, "autoLogAppEventsEnabled": false, "isAutoInitEnabled": true, "iosUserTrackingPermission": "This identifier will be used to deliver personalized ads to you." } ] ] } } ``` -------------------------------- ### Clone the Repository Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/CONTRIBUTING.md Clone the React Native FBSDK Next repository to your local machine for development. ```bash git clone git@github.com:/react-native-fbsdk.next.git ``` -------------------------------- ### Share Content via Dialogs Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/README.md Demonstrates using ShareDialog to share links, photos, and videos. ```javascript // ... import { ShareDialog } from 'react-native-fbsdk-next'; // ... // Build up a shareable link. const shareLinkContent = { contentType: 'link', contentUrl: "https://facebook.com", }; // ... // Share the link using the share dialog. shareLinkWithShareDialog() { var tmp = this; ShareDialog.canShow(this.state.shareLinkContent).then( function(canShow) { if (canShow) { return ShareDialog.show(tmp.state.shareLinkContent); } } ).then( function(result) { if (result.isCancelled) { console.log("Share cancelled"); } else { console.log("Share successful with postId: " + result.postId); } }, function(error) { console.log("Share failed with error: " + error); } ); } ``` ```javascript // ... import { ShareApi } from "react-native-fbsdk-next"; // ... const photoUri = "file://" + "/path/of/photo.png"; const sharePhotoContent = { contentType = "photo", photos: [{ imageUrl: photoUri }], }; // ... ShareDialog.show(tmp.state.sharePhotoContent); ``` ```javascript // ... import { ShareApi } from "react-native-fbsdk-next"; // ... const videoUri = "file://" + "/path/of/video.mp4"; const shareVideoContent = { contentType = "video", video: { localUrl: videoUri }, }; // ... ShareDialog.show(tmp.state.shareVideoContent); ``` -------------------------------- ### Listen for Access Token Changes Source: https://context7.com/thebergamo/react-native-fbsdk-next/llms.txt Sets up a listener to be notified of changes to the user's access token, such as login or logout events. The listener receives the new access token or null if the user logs out. ```javascript // Listen for access token changes const removeListener = AccessToken.addListener((accessToken) => { if (accessToken) { console.log('Access token changed:', accessToken.accessToken); } else { console.log('User logged out'); } }); // Remove the listener when done removeListener(); ``` -------------------------------- ### Log In with Permissions Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/README.md Initiate the login process with specified read permissions. This allows the user to grant your app access to their Facebook data. ```javascript LoginManager.logInWithPermissions(permissions) ``` -------------------------------- ### Configure Android build.gradle for manual linking Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/README.md Add the react-native-fbsdk-next project to the dependencies in your android/app/build.gradle file. ```groovy dependencies { ... implementation project(':react-native-fbsdk-next') } ``` -------------------------------- ### Import FBSDKPackage in MainApplication.java Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/README.md Import the FBSDKPackage class and add it to the list of exported packages in your android/app/src/main/.../MainApplication.java file. ```java import com.facebook.reactnative.androidsdk.FBSDKPackage; ... @Override protected List getPackages() { return Arrays.asList( new MainReactPackage(), new FBSDKPackage() ); } ``` -------------------------------- ### Configure Android settings.gradle for manual linking Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/README.md Update your android/settings.gradle file to include the react-native-fbsdk-next project for manual linking. ```groovy include ':react-native-fbsdk-next' project(':react-native-fbsdk-next').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-fbsdk-next/android') ``` -------------------------------- ### Initialize Facebook SDK on iOS Native Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/README.md Required native initialization in AppDelegate.m for iOS to replace removed auto-initialization functionality. ```objective-c #import // <- Add This Import #import // <- Add This Import #import // <- Add This Import - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [FBSDKApplicationDelegate.sharedInstance initializeSDK]; // <- add this // your other stuff } ``` -------------------------------- ### Spying on LoginManager Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/README.md Demonstrates how to spy on and mock specific methods of the LoginManager for testing purposes. ```javascript import { LoginManager } from "react-native-fbsdk-next" jest.spyOn(LoginManager, "logInWithPermissions").mockImplementation(() => Promise.resolve({ isCancelled: false })) ``` -------------------------------- ### Implement Login Button Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/README.md Standard implementation of the LoginButton component to handle authentication and retrieve access tokens. ```jsx import React, { Component } from 'react'; import { View } from 'react-native'; import { AccessToken, LoginButton } from 'react-native-fbsdk-next'; export default class Login extends Component { render() { return ( { if (error) { console.log("login has error: " + result.error); } else if (result.isCancelled) { console.log("login is cancelled."); } else { AccessToken.getCurrentAccessToken().then( (data) => { console.log(data.accessToken.toString()) } ) } } } onLogoutFinished={() => console.log("logout.")}/> ); } }; ``` -------------------------------- ### Expo Configuration Plugin Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/README.md Configure the react-native-fbsdk-next plugin in your app.json or app.config.js. This is required for Expo projects that need custom native code. ```json { "expo": { "plugins": ["react-native-fbsdk-next"] } } ``` -------------------------------- ### Request Additional Permissions with Login Manager Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/README.md Use the Login Manager to initiate a Facebook login flow, specifying custom permissions. Handle success by checking granted permissions or cancellation. ```javascript // ... import { LoginManager } from "react-native-fbsdk-next"; // ... // Attempt a login using the Facebook login dialog asking for default permissions. LoginManager.logInWithPermissions(["public_profile"]).then( function(result) { if (result.isCancelled) { console.log("Login cancelled"); } else { console.log( "Login success with permissions: " + result.grantedPermissions.toString() ); } }, function(error) { console.log("Login fail with error: " + error); } ); ``` -------------------------------- ### Import required modules for Expo Bare Workflow Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/README.md Necessary imports for integrating the Facebook SDK within an Expo Bare Workflow AppDelegate. ```swift import Expo import React import FBSDKCoreKit // <- Add This import AppTrackingTransparency // <- Add This ``` -------------------------------- ### Mock SDK for Jest Testing Source: https://context7.com/thebergamo/react-native-fbsdk-next/llms.txt Configure Jest to use the library's built-in mocks and simulate login states in test suites. ```javascript // jest.setup.js jest.mock('react-native-fbsdk-next', () => require('react-native-fbsdk-next/jest/mocks').default ); // MyComponent.test.js import { LoginManager, AccessToken } from 'react-native-fbsdk-next'; describe('Facebook Login', () => { it('should handle successful login', async () => { // Mock successful login jest.spyOn(LoginManager, 'logInWithPermissions').mockImplementation(() => Promise.resolve({ isCancelled: false, grantedPermissions: ['public_profile', 'email'], declinedPermissions: [], }) ); jest.spyOn(AccessToken, 'getCurrentAccessToken').mockImplementation(() => Promise.resolve({ accessToken: 'mock_access_token', userID: '12345', applicationID: 'app_id', permissions: ['public_profile', 'email'], declinedPermissions: [], expiredPermissions: [], expirationTime: Date.now() + 3600000, lastRefreshTime: Date.now(), dataAccessExpirationTime: Date.now() + 7776000000, }) ); // Test your component that uses Facebook login const result = await LoginManager.logInWithPermissions(['public_profile']); expect(result.isCancelled).toBe(false); const token = await AccessToken.getCurrentAccessToken(); expect(token.accessToken).toBe('mock_access_token'); }); it('should handle cancelled login', async () => { jest.spyOn(LoginManager, 'logInWithPermissions').mockImplementation(() => Promise.resolve({ isCancelled: true }) ); const result = await LoginManager.logInWithPermissions(['public_profile']); expect(result.isCancelled).toBe(true); }); }); ``` -------------------------------- ### Fixing Build Errors with Swift/Objective-C Coordination Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/README.md When encountering 'Undefined symbols' errors related to Swift frameworks in Xcode, ensure proper coordination between Swift and Objective-C. This can be achieved by creating a bridging header or by adjusting the Podfile's postinstall script to manage search paths. ```bash $(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME) $(TOOLCHAIN_DIR)/usr/lib/swift-5.0/$(PLATFORM_NAME) ``` -------------------------------- ### Activate App on applicationDidBecomeActive Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/README.md Ensures app events are tracked when the application becomes active. ```swift open override func applicationDidBecomeActive(_ application: UIApplication) { super.applicationDidBecomeActive(application) AppEvents.shared.activateApp() } ``` -------------------------------- ### Perform Standard Facebook Login Source: https://context7.com/thebergamo/react-native-fbsdk-next/llms.txt Initiates a standard Facebook login flow requesting specified permissions. Handles cancellation and logs granted/declined permissions. Returns the access token upon success. ```javascript import { LoginManager, AccessToken, AuthenticationToken } from 'react-native-fbsdk-next'; import { Platform } from 'react-native'; // Standard login with permissions async function loginWithFacebook() { try { const result = await LoginManager.logInWithPermissions(['public_profile', 'email']); if (result.isCancelled) { console.log('Login cancelled'); return null; } console.log('Login success with permissions:', result.grantedPermissions); console.log('Declined permissions:', result.declinedPermissions); // Get the access token after successful login const accessToken = await AccessToken.getCurrentAccessToken(); return accessToken; } catch (error) { console.log('Login failed with error:', error); return null; } } ``` -------------------------------- ### Log Purchase Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/README.md Log a purchase event with the amount, currency, and optional parameters. This is essential for tracking in-app purchases and revenue. ```javascript AppEventsLogger.logPurchase(purchaseAmount, currency, parameters) ``` -------------------------------- ### Log events and user data with AppEventsLogger Source: https://context7.com/thebergamo/react-native-fbsdk-next/llms.txt Use these methods to track custom events, standard events, purchases, and manage user identity for analytics. Ensure the module is imported before calling any logging methods. ```javascript import { AppEventsLogger } from 'react-native-fbsdk-next'; // Log a custom event AppEventsLogger.logEvent('button_clicked', { button_name: 'signup' }); // Log event with a value AppEventsLogger.logEvent('level_completed', 100, { level: '5', score: '9500' }); // Log standard events using predefined constants AppEventsLogger.logEvent(AppEventsLogger.AppEvents.CompletedRegistration, { [AppEventsLogger.AppEventParams.RegistrationMethod]: 'email', }); AppEventsLogger.logEvent(AppEventsLogger.AppEvents.ViewedContent, { [AppEventsLogger.AppEventParams.ContentID]: 'product_123', [AppEventsLogger.AppEventParams.ContentType]: 'product', [AppEventsLogger.AppEventParams.Currency]: 'USD', }); AppEventsLogger.logEvent(AppEventsLogger.AppEvents.AddedToCart, { [AppEventsLogger.AppEventParams.ContentID]: 'sku_12345', [AppEventsLogger.AppEventParams.NumItems]: '1', [AppEventsLogger.AppEventParams.Currency]: 'USD', }); // Log a purchase AppEventsLogger.logPurchase(29.99, 'USD', { product_id: 'premium_subscription', quantity: '1', }); // Log push notification open AppEventsLogger.logPushNotificationOpen({ fb_push_payload: '{"campaign":"holiday_sale"}', }); // Log product catalog item (for dynamic ads) AppEventsLogger.logProductItem( 'SKU_12345', // itemID 'in_stock', // availability: 'in_stock' | 'out_of_stock' | 'preorder' | 'avaliable_for_order' | 'discontinued' 'new', // condition: 'new' | 'refurbished' | 'used' 'Premium Widget', // description 'https://example.com/image.jpg', // imageLink 'https://example.com/product', // link 'Widget Pro', // title 99.99, // priceAmount 'USD', // currency '123456789012', // gtin (optional) 'WIDGET-001', // mpn (optional) 'WidgetCo', // brand (optional) { color: 'blue' } // additional parameters (optional) ); // Set user ID for cross-device tracking AppEventsLogger.setUserID('user_12345'); // Get current user ID const userId = await AppEventsLogger.getUserID(); console.log('Current user ID:', userId); // Clear user ID AppEventsLogger.setUserID(null); // Set user data for advanced matching AppEventsLogger.setUserData({ email: 'user@example.com', firstName: 'John', lastName: 'Doe', phone: '+15551234567', dateOfBirth: '1990-01-15', gender: 'm', // 'm' or 'f' city: 'San Francisco', state: 'CA', zip: '94102', country: 'US', }); // Get anonymous ID const anonymousId = await AppEventsLogger.getAnonymousID(); // Get advertiser ID const advertiserId = await AppEventsLogger.getAdvertiserID(); // Get attribution ID (Android only) const attributionId = await AppEventsLogger.getAttributionID(); // Configure flush behavior AppEventsLogger.setFlushBehavior('auto'); // 'auto' | 'explicit_only' // Manually flush events to Facebook AppEventsLogger.flush(); // iOS: Set push notification device token AppEventsLogger.setPushNotificationsDeviceToken('device_token_string'); // Android: Set push notification registration ID AppEventsLogger.setPushNotificationsRegistrationId('fcm_registration_id'); ``` -------------------------------- ### Manually Set Access Token Source: https://context7.com/thebergamo/react-native-fbsdk-next/llms.txt Allows manually setting an access token, which is useful for restoring user sessions without requiring a new login. ```javascript // Manually set an access token (useful for restoring sessions) AccessToken.setCurrentAccessToken({ accessToken: 'your_token_string', permissions: ['public_profile', 'email'], declinedPermissions: [], expiredPermissions: [], applicationID: 'your_app_id', userID: 'user_id', expirationTime: Date.now() + 3600000, // 1 hour from now lastRefreshTime: Date.now(), dataAccessExpirationTime: Date.now() + 7776000000, // 90 days }); ``` -------------------------------- ### Add Swift Imports for Facebook SDK Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/README.md Include these imports at the top of your `/ios/PROJECT/AppDelegate.swift` file when using React Native 0.77 and above. ```swift import FBSDKCoreKit // <- Add This Import import AppTrackingTransparency // <- Add This Import // Remove this if present: // import FacebookCore // <- REMOVE if present ``` -------------------------------- ### Log App Event Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/README.md Log a custom app event with optional parameters. This allows for detailed tracking of user interactions within the app. ```javascript AppEventsLogger.logEvent(eventName, parameters) ``` -------------------------------- ### Configure LoginManager Settings Source: https://context7.com/thebergamo/react-native-fbsdk-next/llms.txt Sets the default audience for posts and the login behavior for Android. Retrieves the current default audience. ```javascript // Set default audience for posts LoginManager.setDefaultAudience('friends'); // 'friends' | 'everyone' | 'only_me' // Get current default audience const audience = await LoginManager.getDefaultAudience(); // Android only: Set login behavior LoginManager.setLoginBehavior('native_with_fallback'); // 'native_with_fallback' | 'native_only' | 'web_only' ``` -------------------------------- ### Share Content via Share API Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/README.md Uses ShareApi to share content directly. Requires the publish_actions permission. ```javascript // ... import { ShareApi } from 'react-native-fbsdk-next'; // ... // Build up a shareable link. const shareLinkContent = { contentType: "link", contentUrl: "https://facebook.com", }; // ... // Share using the share API. ShareApi.canShare(this.state.shareLinkContent).then( var tmp = this; function(canShare) { if (canShare) { return ShareApi.share(tmp.state.shareLinkContent, "/me", "Some message."); } } ).then( function(result) { console.log("Share with ShareApi success."); }, function(error) { console.log("Share with ShareApi failed with error: " + error); } ); ``` -------------------------------- ### Implement Facebook Login UI Source: https://context7.com/thebergamo/react-native-fbsdk-next/llms.txt Use the LoginButton component to handle authentication. Includes logic for standard login and iOS Limited Login tracking. ```jsx import React from 'react'; import { View, Text, Platform } from 'react-native'; import { LoginButton, AccessToken, AuthenticationToken } from 'react-native-fbsdk-next'; function FacebookLoginScreen() { const handleLoginFinished = async (error, result) => { if (error) { console.log('Login error:', error); return; } if (result.isCancelled) { console.log('Login was cancelled'); return; } console.log('Login successful!'); console.log('Granted permissions:', result.grantedPermissions); // Get token based on login tracking mode if (Platform.OS === 'ios') { const authToken = await AuthenticationToken.getAuthenticationTokenIOS(); if (authToken) { console.log('iOS Limited Login token:', authToken.authenticationToken); } else { const accessToken = await AccessToken.getCurrentAccessToken(); console.log('Standard access token:', accessToken?.accessToken); } } else { const accessToken = await AccessToken.getCurrentAccessToken(); console.log('Access token:', accessToken?.accessToken); } }; const handleLogoutFinished = () => { console.log('User logged out'); }; return ( Login with Facebook {/* Standard Login Button */} {/* Limited Login Button (iOS 14+ ATT compliance) */} ); } export default FacebookLoginScreen; ``` -------------------------------- ### Generate Android Key Hash Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/README.md Command to generate a base64-encoded key hash from a SHA-1 fingerprint for Android app signing. ```bash echo YOUR_SHA1_HERE | xxd -r -p | openssl base64 ``` -------------------------------- ### Add Objective-C Imports for Facebook SDK Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/README.md Include these imports in your `/ios/PROJECT/AppDelegate.m` file when using React Native versions 0.76 and below. ```objective-c #import #import #import ``` -------------------------------- ### Manually link iOS library with CocoaPods Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/README.md Add this line to your Podfile to manually link the react-native-fbsdk-next library using CocoaPods. ```ruby pod 'react-native-fbsdk-next', :path => '../node_modules/react-native-fbsdk-next' ``` -------------------------------- ### Perform Graph API Requests with GraphRequest and GraphRequestManager Source: https://context7.com/thebergamo/react-native-fbsdk-next/llms.txt Use these functions to fetch user data, post content, manage batches, or specify API versions. Ensure GraphRequestManager is initialized to execute the requests. ```javascript import { GraphRequest, GraphRequestManager } from 'react-native-fbsdk-next'; // Simple Graph API request to get user info function fetchUserInfo() { const infoRequest = new GraphRequest( '/me', { parameters: { fields: { string: 'id,name,email,picture.type(large)', }, }, }, (error, result) => { if (error) { console.log('Error fetching user info:', error); return; } console.log('User info:', result); console.log('Name:', result.name); console.log('Email:', result.email); console.log('Profile picture:', result.picture?.data?.url); } ); new GraphRequestManager().addRequest(infoRequest).start(); } // Graph API request with custom access token function fetchWithCustomToken(accessToken) { const request = new GraphRequest( '/me/friends', { accessToken: accessToken, parameters: { fields: { string: 'id,name,picture', }, limit: { string: '10', }, }, }, (error, result) => { if (error) { console.log('Error:', error); return; } console.log('Friends:', result.data); } ); new GraphRequestManager().addRequest(request).start(); } // POST request to publish content function postToFeed(message) { const postRequest = new GraphRequest( '/me/feed', { httpMethod: 'POST', parameters: { message: { string: message, }, }, }, (error, result) => { if (error) { console.log('Post failed:', error); return; } console.log('Post successful, ID:', result.id); } ); new GraphRequestManager().addRequest(postRequest).start(); } // Batch multiple requests function fetchMultipleResources() { const manager = new GraphRequestManager(); const userRequest = new GraphRequest( '/me', { parameters: { fields: { string: 'id,name' } } }, (error, result) => { if (error) { console.log('User request error:', error); } else { console.log('User:', result); } } ); const photosRequest = new GraphRequest( '/me/photos', { parameters: { fields: { string: 'id,picture' }, limit: { string: '5' } } }, (error, result) => { if (error) { console.log('Photos request error:', error); } else { console.log('Photos:', result.data); } } ); manager .addRequest(userRequest) .addRequest(photosRequest) .addBatchCallback((error, result) => { console.log('Batch completed'); if (error) { console.log('Batch error:', error); } }) .start(30000); // optional timeout in milliseconds } // Using specific Graph API version function fetchWithVersion() { const request = new GraphRequest( '/me', { version: 'v18.0', parameters: { fields: { string: 'id,name' }, }, }, (error, result) => { console.log('Result:', result); } ); new GraphRequestManager().addRequest(request).start(); } ``` -------------------------------- ### Log Push Notification Open Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/README.md Log when a push notification is opened. This helps in analyzing the effectiveness of push notification campaigns. ```javascript AppEventsLogger.logPushNotificationOpen(payload) ``` -------------------------------- ### Set User Data Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/README.md Set user data for event logging. This can include information like gender, birthday, and locale to enrich event data. ```javascript AppEventsLogger.setUserData(userData) ``` -------------------------------- ### Configure ShareDialog Mode Source: https://context7.com/thebergamo/react-native-fbsdk-next/llms.txt Sets the mode for the ShareDialog. Available modes include 'automatic', 'native', 'web', 'browser', 'webview', and 'feed'. ```javascript ShareDialog.setMode('automatic'); // 'automatic' | 'native' | 'web' | 'browser' | 'webview' | 'feed' ``` -------------------------------- ### Log App Events Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/README.md Uses AppEventsLogger to track purchases and standard events. ```javascript // ... import { AppEventsLogger } from "react-native-fbsdk-next"; // ... // Log a $15 purchase. AppEventsLogger.logPurchase(15, "USD", { param: "value" }); // Log standard event. e.g. completed registration AppEventsLogger.logEvent(AppEventsLogger.AppEvents.CompletedRegistration, { [AppEventsLogger.AppEventParams.RegistrationMethod]: "email", }); ``` -------------------------------- ### Limited Login with Authentication Token (iOS) Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/README.md Implement limited login on iOS using the LoginButton, which provides an AuthenticationToken instead of an AccessToken when `loginTrackingIOS` is set to 'limited'. This is required for iOS versions >= 13.0.0. An optional nonce can be provided for server-side validation. ```jsx import React, { Component } from 'react'; import { Platform, View } from 'react-native'; import { AccessToken, AuthenticationToken, LoginButton, } from 'react-native-fbsdk-next'; export default class Login extends Component { render() { return ( { if (error) { console.log("login has error: " + result.error); } else if (result.isCancelled) { console.log("login is cancelled."); } else { if (Platform.OS === "ios") { AuthenticationToken.getAuthenticationTokenIOS().then((data) => { console.log(data?.authenticationToken); }); } else { AccessToken.getCurrentAccessToken().then((data) => { console.log(data?.accessToken.toString()); }); } } }} onLogoutFinished={() => console.log("logout.")} loginTrackingIOS="limited" nonceIOS="my_nonce" // Optional /> ); } } ``` -------------------------------- ### Log Purchase Event with AEM Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/README.md Logs a purchase event using AppEventsLogger and also logs it to AEM using AEMReporterIOS. Ensure event names match for AEM. ```typescript LogFBPurchase = (purchaseAmount: number, currencyCode: string, parameters?: Params | undefined) => { AppEventsLogger.logPurchase(purchaseAmount, currencyCode, parameters); AEMReporterIOS.logAEMEvent("fb_mobile_purchase", purchaseAmount, currencyCode, parameters); } ``` -------------------------------- ### Configure ShareDialog Error Handling Source: https://context7.com/thebergamo/react-native-fbsdk-next/llms.txt Enables or disables failing the share operation when data errors occur. Set to true to fail on data errors. ```javascript ShareDialog.setShouldFailOnDataError(true); ``` -------------------------------- ### Authenticate with Limited Login Source: https://github.com/thebergamo/react-native-fbsdk-next/blob/master/README.md Uses LoginManager to request permissions and retrieve either an AuthenticationToken on iOS or an AccessToken on other platforms. ```javascript //... import { AccessToken, AuthenticationToken, LoginManager, } from "react-native-fbsdk-next"; //... try { const result = await LoginManager.logInWithPermissions( [ "public_profile", "email", ], "limited", "my_nonce", // Optional ); console.log(result); if (Platform.OS === "ios") { // This token **cannot** be used to access the Graph API. // https://developers.facebook.com/docs/facebook-login/limited-login/ const result = await AuthenticationToken.getAuthenticationTokenIOS(); console.log(result?.authenticationToken); } else { // This token can be used to access the Graph API. const result = await AccessToken.getCurrentAccessToken(); console.log(result?.accessToken); } } catch (error) { console.log(error); } //... ```