如何将Facebook SDK安装到React Native Android或iOS App中

万选
2023-12-01

So I made this snarky tweet at 4 a.m. This is my peace offering.

因此,我在凌晨4点发布了这条棘手的推文。这是我的平安祭。

If you’re a native Android or iOS developer and are already familiar with their respective ecosystems, this blog post probably won’t do you much good.

如果您是本地Android或iOS开发人员,并且已经熟悉各自的生态系统,则此博客文章可能对您没有多大帮助。

But if you’re a JavaScript developer who doesn’t know what an Info.plist or a strings.xml file is — and you’d sooner wait 45 minutes for npm install to finish than open up Xcode — this guide is for you.

但是,如果您是不知道Info.plist或strings.xml文件是什么JavaScript开发人员,并且与打开Xcode相比,您需要等待45分钟才能完成npm安装 ,所以该指南非常适合您。

Note that this is a just an excerpt from my much more comprehensive React.js Program’s React Native course.

请注意,这只是我更全面的React.js程序React Native课程的摘录。

Let’s assume you’re reading this because you’re more concerned with “how” than “why.” So, unlike my typical posts, this one will be heavy on implementation details and light on understanding the abstractions.

假设您正在阅读本文,是因为您更关心“如何”而不是“为什么”。 因此,与我的典型文章不同,该文章将重点介绍实现细节和对抽象的理解。

I’m also assuming you’re using React Native .29 or above. If you’re using e version older than that, well, you have bigger problems than getting this tutorial to work.

我还假设您正在使用React Native .29或更高版本。 如果您使用的e版本早于该版本,那么与使本教程正常工作相比,您会遇到更大的问题。

We’re going to use Facebook’s “react-native-fbsdk” library, which is just a wrapper around the Facebook SDKs for Android and iOS. It will give us access to Facebook login, sharing, graph requests, and app events.

我们将使用Facebook的“ react-native-fbsdk ”库,该库只是针对Android和iOS的Facebook SDK的包装。 它将使我们能够访问Facebook登录,共享,图表请求和应用程序事件。

In your terminal run:

在您的终端运行中:

npm install --save react-native-fbsdk

Next up, we need to do some linking.

接下来,我们需要进行一些链接。

Again, in your terminal run:

同样,在终端运行:

react-native link

Now let’s register a new app with Facebook.

现在,让我们在Facebook上注册一个新应用。

Header over to Facebook’s developers site and “Add a New App”.

前往Facebook的开发人员网站并“添加新应用”。

When you see this screen select iOS…

当您看到此屏幕时,请选择iOS…

…type in the name of your project, then hit the main submit button which at the time of this writing says “Create new Facebook App Id.” Be sure to enter in a contact email address and select a Category.

…输入您的项目名称,然后点击主要提交按钮,在撰写本文时,该按钮显示为“创建新的Facebook应用ID”。 确保输入联系人电子邮件地址并选择类别。

If you’re lucky, at this point you’ll get a fun little game about matching Tigers or watches. Facebook is just full of fun micro experiences ?.

如果幸运的话,这时您将获得一个有趣的小游戏,关于如何搭配Tigers或手表。 Facebook只是充满乐趣的微体验?。

Once at this view, you’re going to do exactly what is says, and download the SDK to your ~/Documents folder.

进入此视图后,您将按照显示的内容进行操作,然后将SDK下载到〜/ Documents文件夹中

Coming from the web, this is going to feel super strange. But it’s the only way I could get the SDK tied up properly without having to resort to using Pods.

来自网络,这会感觉很奇怪。 但这是我可以正确捆绑SDK而不用求助于Pods的唯一方法。

At this point you should have successfully installed “react-native-fbsdk” and created a new iOS Facebook app. The FacebookSDK should be located in the ~/Documents folder of your computer.

此时,您应该已经成功安装了“ react-native-fbsdk”并创建了一个新的iOS Facebook应用。 FacebookSDK应该位于计算机的〜/ Documents文件夹中。

Now for the moment we’ve been training for.

现在,我们一直在为此训练。

Go to your project and double click on YourAppName.xcodeproj project to open it up in Xcode.

转到您的项目,然后双击YourAppName.xcodeproj项目,以Xcode打开它。

Once you have your project opened in Xcode, right click on your project’s name in the left sidebar and select “New Group” and type in “Frameworks”.

在Xcode中打开项目后,右键单击左侧栏中的项目名称,然后选择“ 新建组 ”,然后键入“ 框架 ”。

Then open up your ~Documents/FacebookSDK folder from earlier and drag FBSDKCoreKit.Framework, FBSDKLoginKit.Framework, FBSDKShareKit.Framework into the Frameworks group you just created. The end result should look like this,

然后从之前打开〜Documents / FacebookSDK文件夹,并将FBSDKCoreKit.FrameworkFBSDKLoginKit.FrameworkFBSDKShareKit.Framework拖到您刚刚创建的Frameworks组中。 最终结果应如下所示:

Now, click on the “Build Settings” tag (pictured below) then search for “Framework Search Paths”. Once you find it add “~/Documents/FacebookSDK”. (To get the little popup box double click on the highlighted line right below the word “Spero” then click the + button to add the text).

现在, 单击“ Build Settings”标签 (如下图所示),然后搜索“ Framework Search Paths ”。 找到它后,添加“ 〜/ Documents / FacebookSDK ”。 (要获得小的弹出框,请双击单词“ Spero”下方的突出显示的行,然后单击+按钮添加文本)。

Now we need to dive into our Info.plist. For this step we’ll need our Facebook App ID number. To get this, head back over to your Facebook developer dashboard and it will be on the home screen under “App ID”.

现在,我们需要深入研究Info.plist。 对于此步骤,我们需要我们的Facebook App ID号。 为此,请返回您的Facebook开发人员仪表板,它将显示在主屏幕上的“应用程序ID”下。

Now open up your app in your preferred IDE and then open up the “Info.plist” file located in “ios/YourAppName

现在,在首选的IDE中打开您的应用程序,然后打开“ ios / YourAppName ”中的“ Info.plist ”文件

Now, right below this strange line

现在,在这条奇怪的线的正下方

<string>????</string>

add this code,

添加此代码,

<key>CFBundleURLTypes</key> <array>  <dict>   <key>CFBundleURLSchemes</key>   <array>    <string>fbYOUR-APP-ID</string>   </array>  </dict> </array> <key>FacebookAppID</key> <string>YOUR-APP-ID</string> <key>FacebookDisplayName</key> <string>YOUR-FACEBOOK-DISPLAY-NAME</string> <key>LSApplicationQueriesSchemes</key> <array>  <string>fbapi</string>  <string>fb-messenger-api</string>  <string>fbauth2</string>  <string>fbshareextension</string> </array>

Be sure to swap out “YOUR-APP-ID” with your Facebook APP Id and “YOUR-FACEBOOK-DISPLAY-NAME” with, well, your Facebook app display name.

确保将“ YOUR-APP-ID ”与您的Facebook APP ID和“ YOUR-FACEBOOK-DISPLAY-NAME ”与您的Facebook应用显示名称互换。

Now head back to Xcode and grab your “Bundle Identifier” number located in the “General” tab.

现在返回Xcode并获取位于“ 常规 ”选项卡中的“ Bundle Identifier ”编号。

Once you have that, copy it to your clipboard.

一旦有了它,将其复制到剪贴板。

Now head over to your Facebook Developer dashboard again and click on “Settings” ->; “Basic” -> “+Add Platform” and select “iOS”.

现在再次转到您的Facebook Developer仪表板,然后单击“ 设置 ”-> “基本 ”- >“ +添加Pl格式”并选择 “ iOS”。

Once you select iOS you’ll see a place to enter in your “Bundle ID” you just got from Xcode. Do that and be sure to select “Save Changes”.

选择iOS后,您会看到一个输入Xcode的“ Bundle ID ”的地方。 这样做,并确保选择“ Save Changes ”。

Now head back to your text editor and open up “ios/PROJECT-NAME/AppDelegate.m

现在回到您的文本编辑器并打开“ ios / PROJECT-NAME / AppDelegate.m

Right above “@implementation AppDelegate” you need to import FBSDKCoreKit. Go ahead and add

在“ @implementation AppDelegate ”上方,您需要导入FBSDKCoreKit。 继续添加

#import <FBSDKCoreKit/FBSDKCoreKit.h>

Now right above the “@end” line (and after the didFinishLaunchingWithOptions block) add this code,

现在,在“ @end ”行的上方(在didFinishLaunchingWithOptions块之后)添加此代码,

- (void)applicationDidBecomeActive:(UIApplication *)application {  [FBSDKAppEvents activateApp];}
- (BOOL)application:(UIApplication *)application            openURL:(NSURL *)url  sourceApplication:(NSString *)sourceApplication         annotation:(id)annotation {  return [[FBSDKApplicationDelegate sharedInstance] application:application                                                         openURL:url                                               sourceApplication:sourceApplication                                                      annotation:annotation];}

So your final AppDelegate.m file will look something like this (changes in bold),

因此,您最终的AppDelegate.m文件将类似于以下内容(以粗体显示 ),

#import "AppDelegate.h"
#import "RCTBundleURLProvider.h"#import "RCTRootView.h"
#import <FBSDKCoreKit/FBSDKCoreKit.h>
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{  NSURL *jsCodeLocation;
jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index.ios" fallbackResource:nil];
RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation                                                      moduleName:@"Spero"                                               initialProperties:nil                                                   launchOptions:launchOptions];  rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];  UIViewController *rootViewController = [UIViewController new];  rootViewController.view = rootView;  self.window.rootViewController = rootViewController;  [self.window makeKeyAndVisible];  return YES;}
- (void)applicationDidBecomeActive:(UIApplication *)application {  [FBSDKAppEvents activateApp];}
- (BOOL)application:(UIApplication *)application            openURL:(NSURL *)url  sourceApplication:(NSString *)sourceApplication         annotation:(id)annotation {  return [[FBSDKApplicationDelegate sharedInstance] application:application                                                         openURL:url                                               sourceApplication:sourceApplication                                                      annotation:annotation];}
@end

Good news is that’s all you need to do for iOS. If you’re not building an Android app as well, you’re all set. However, if you are (or if you ever plan on) building an Android app as well, continue on.

好消息是,这是您需要为iOS做的所有事情。 如果您还没有构建Android应用,那么您已经准备就绪。 但是,如果您也(或计划)构建Android应用,请继续。

**Update: If at this point you’re still getting an error, it may be due to some recent changes in iOS 10 and Xcode 8. Head over to the “Capabilities” section in Xcode and enable “Keychain Sharing”.

**更新:如果此时您仍然遇到错误,则可能是由于iOS 10和Xcode 8中的某些最新更改所致。转到Xcode中的“功能”部分并启用“钥匙串共享”。

**Now onto Android.

**现在使用Android。

Now in your text editor head over to your “MainApplication.java” file located at “android/app/src/main/java/com/<project name>/”

现在,在文本编辑器中,转到位于“ android / app / src / main / java / com / <项目名称 > /”的“ MainApplication.java ”文件

After all of the other imports in MainApplication.java, add the following imports.

MainApplication.java中的所有其他导入之后 ,添加以下导入。

import com.facebook.CallbackManager;import com.facebook.FacebookSdk;import com.facebook.reactnative.androidsdk.FBSDKPackage;

Now inside the MainApplication class, add the following properties,

现在在MainApplication类中,添加以下属性,

private static CallbackManager mCallbackManager = CallbackManager.Factory.create();
protected static CallbackManager getCallbackManager() {    return mCallbackManager;}

Now go ahead and head to the bottom of your MainApplication class and add this Override to the class.

现在继续前进,进入MainApplication类的底部,并将此Override添加到类中。

@Overridepublic void onCreate() {  super.onCreate();  FacebookSdk.sdkInitialize(getApplicationContext());}

Now the last step in this file is you need to include the FBSDKPackage to your Array of React packages. Find the code that looks like this,

现在,该文件的最后一步是您需要将FBSDKPackage包含到您的React数组数组中。 找到看起来像这样的代码,

@Overrideprotected List<ReactPackage> getPackages() {   return Arrays.<ReactPackage>asList(    new MainReactPackage()   );}

and go ahead and add “new FBSDKPackage(mCallbackManager)” as a new list item on that array.

并继续添加“ new FBSDKPackage(mCallbackManager)”作为该阵列上的新列表项。

Once you’re finished, your code should look similar to this (changes are bold)

完成后,您的代码应类似于此(更改为粗体)

package com.spero;
import android.app.Application;import android.util.Log;
import com.facebook.react.ReactApplication;import com.oblador.vectoricons.VectorIconsPackage;import com.facebook.reactnative.androidsdk.FBSDKPackage;import com.facebook.react.ReactInstanceManager;import com.facebook.react.ReactNativeHost;import com.facebook.react.ReactPackage;import com.facebook.react.shell.MainReactPackage;
import java.util.Arrays;import java.util.List;
import com.facebook.CallbackManager;import com.facebook.FacebookSdk;import com.facebook.reactnative.androidsdk.FBSDKPackage;
public class MainApplication extends Application implements ReactApplication {
private static CallbackManager mCallbackManager = CallbackManager.Factory.create();
protected static CallbackManager getCallbackManager() {    return mCallbackManager;  }
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {    @Override    protected boolean getUseDeveloperSupport() {      return BuildConfig.DEBUG;    }
@Override    protected List<ReactPackage> getPackages() {      return Arrays.<ReactPackage>asList(          new MainReactPackage(),          new FBSDKPackage(mCallbackManager)      );    }  };
@Override  public ReactNativeHost getReactNativeHost() {      return mReactNativeHost;  }
@Override  public void onCreate() {    super.onCreate();    FacebookSdk.sdkInitialize(getApplicationContext());  }}

Alright we’re really close. Now head over to MainActivity.java (located at “android/app/src/main/java/com/<project name>/” and do the following,

好吧,我们真的很接近。 现在转到MainActivity.java(位于“ android / app / src / main / java / com / <项目名称> /”,然后执行以下操作,

First import android.content.Intent;

首先导入android.content.Intent;

import android.content.Intent;

next, add this Override to your MainActivity class

接下来,将此覆盖添加到您的MainActivity类中

@Overridepublic void onActivityResult(int requestCode, int resultCode, Intent data) {        super.onActivityResult(requestCode, resultCode, data);        MainApplication.getCallbackManager().onActivityResult(requestCode, resultCode, data);    }

Your final code will look like this (changes in bold)

您的最终代码将如下所示(以粗体显示)

package com.spero;
import com.facebook.react.ReactActivity;
import android.content.Intent;
public class MainActivity extends ReactActivity {
@Override    public void onActivityResult(int requestCode, int resultCode, Intent data) {        super.onActivityResult(requestCode, resultCode, data);        MainApplication.getCallbackManager().onActivityResult(requestCode, resultCode, data);    }
@Override    protected String getMainComponentName() {        return "Spero";    }}

Take a few deep breaths. We’re just a few changes away from Valhalla.

深吸一口气。 与Valhalla仅有几处距离。

Head over to “strings.xml” located at “android/app/src/main/res/values/strings.xml” and add a new string with your facebook app id.

头部到位于“ 机器人/应用/ src目录/主/ RES /价值/ strings.xml中”“ 的strings.xml”,并添加新的字符串与您的Facebook应用程序ID。

<string name="facebook_app_id">YOUR_APP_ID</string>

Your strings.xml file will now look similar to this,

您的strings.xml文件现在看起来与此类似,

<resources>    <string name="app_name">NameOfYourApp&lt;/string>    <string name="facebook_app_id">YOUR-FACEBOOK-ID</string></resources>

One. More. File. To. Go.

之一。 更多。 文件。 至。 走。

Head over to AndroidManifest.xml located at “android/app/src/main” and add the following code right before </application>

转到位于“ android / app / src / main ”的AndroidManifest.xml并在</ applicati on>之前添加以下代码

<activity android:name="com.facebook.FacebookActivity"        android:configChanges=               "keyboard|keyboardHidden|screenLayout|screenSize|orientation"        android:theme="@style/com_facebook_activity_theme"        android:label="@string/app_name" />
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>

And with those 48 easy, fool proofs steps, you’re good to go!

有了这48个简单,简单的证明步骤,您就可以开始了!

To see all these changes in a real project, dive into the changes files above in this project.

要查看真实项目中的所有这些更改,请深入查看该项目中上面的更改文件

Originally published at tylermcginnis.com.

最初发布于tylermcginnis.com

翻译自: https://www.freecodecamp.org/news/installing-the-facebook-sdk-into-a-react-native-android-and-ios-app-69439bd97a99/

 类似资料: