How to setup Login Facebook in React Native
Facebook login is an overwhelming combination of a lot of information that drives nowhere. I creating the ultimate guide for creating in both versions Android / iOS, in youtube there are some videos but aren’t updated. I want to share with you what problems I faced.
Starting with Android Version the steps according to the sample of the official page are:
react-native install react-native-fbsdk
react-native link react-native-fbsdk
And now you can run the Android App!? Are you serious?
First in you don’t need anymore to link the fbsdk, and also there are a lot of steps that are omitted there.
So basically once you create a new project or your current project and want to make a Facebook login with Android.
react-native init loginFacebookSample
In my case I prefer to use the lastest version of buildToolsVersion for Android in all the libraries. So in order to do so what I do is go to:
Android/app/build.gradle
And the check this:
buildToolsVersion "27.0.2"
in this case I am using the lastest version. Also we have to check in each libraries in the folder:
node_modules
It is tedious to search in each folder of a looong list of libraries. So I prefer to use a Regex (Regular Expression) in order to find it:
buildToolsVersion ("|')\d{2}.\d{1}.\d{1}("|')
So with that expression you have all the buildToolsVersion versions in your folder node_modules.
You change to the version that you are using in the Android SDK. In our case:
buildToolsVersion "27.0.2"
Or you might just want to read this and you avoid to do it over and over again.
Once you have that you have set up all what you need just to run the first time:
react-native run-android
So now, we start with:
react-native install react-native-fbsdk
Also we don’t need to type this:
react-native link react-native-fbsdk
It is already linked, if you don’t trust me try it :).
Once we have to go this link:
First you have to create a new application and confirm that you are a human (Sorry Martians you can’t complete this part).
Enter in Login Facebook:
Before you follow this steps is necessary to add some code to the MainApplication and MainActivity. Those steps are in the github page this. In our case we should follow RN above 0.29.
Go to MainApplication.java and MainActivity.java under app/src/main/java/com/<project name>/ to complete setup.
In MainApplication.java,
Add an instance variable of type CallbackManager and its getter.
import com.facebook.CallbackManager;
import com.facebook.FacebookSdk;
import com.facebook.reactnative.androidsdk.FBSDKPackage;
import com.facebook.appevents.AppEventsLogger;
...
public class MainApplication extends Application implements ReactApplication {
private static CallbackManager mCallbackManager = CallbackManager.Factory.create();
protected static CallbackManager getCallbackManager() {
return mCallbackManager;
}
//...
import com.facebook.FacebookSdk;
import com.facebook.reactnative.androidsdk.FBSDKPackage;
import com.facebook.appevents.AppEventsLogger;
...
public class MainApplication extends Application implements ReactApplication {
private static CallbackManager mCallbackManager = CallbackManager.Factory.create();
protected static CallbackManager getCallbackManager() {
return mCallbackManager;
}
//...
Override onCreate() method
@Override
public void onCreate() {
super.onCreate();
FacebookSdk.sdkInitialize(getApplicationContext());
// If you want to use AppEventsLogger to log events.
AppEventsLogger.activateApp(this);
}
public void onCreate() {
super.onCreate();
FacebookSdk.sdkInitialize(getApplicationContext());
// If you want to use AppEventsLogger to log events.
AppEventsLogger.activateApp(this);
}
Register sdk package in method getPackages().
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new FBSDKPackage(mCallbackManager)
);
}
};
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new FBSDKPackage(mCallbackManager)
);
}
};
In MainActivity.java
Override onActivityResult() method
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);
}
//...
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);
}
//...
Then you have to “follow the steps” that was everyone said! I am not completely sure that. So you can continue to and skip the first 2 steps. Now we have to fill this:
So basically it said that we need the package of the project and the default activity. What the hell is that!??
You can find it in the AndroidManifest.xml of your android project, which is the skeleton of your Android project. You can find in this path:
Android/app/src/main/AndroidManifest.xml
Or if you are in VSCode you can press cmd + P (Mac) or control + P (Windows) and type AndroidManifest.XML and there you go.
So in this file you see at the top something like this:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.samplelogin"
android:versionCode="1"
android:versionName="1.0">
package="com.samplelogin"
android:versionCode="1"
android:versionName="1.0">
The package name is com.sampleLogin and we have the first part.
The second is your MainActivity which in RN (React Native) is .MainActivity
And we are done with that part. Cool. There are gonna ask you if you want to continue because our application is not register (Of course not!, we are just building our first login, so calm down).
Now in the 4 step they are gonna ask you about our hashes!?? WTF? Man I just want to create a simple Login with Facebook! Chill out!
So yes, we need a keytool for making a simple Login with Facebook. If you are in a Mac this step is not really hard.
You just copy and paste in the console:
keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64
They are gonna ask you for a password. Again it is really necessary!? We use something that we can remember. Like 1234 (I know it is not the best password, but we just want to keep going). In our console we will see in something like this:
And we will see a 28 characters that ends with =. So you put that in your hashes. You also need two hashes one for development and one for release. It is better that you do both so you don’t have to deal with that anymore.
So with that 2 hashes we are done. In Windows that keytool might take a while because probably the code is not going to work. But that’s another tutorial for it!
So in step 5. They are gonna ask you about login unique. We just skip that.
Step 6. We have to edit of AndroidManifest.XML folder. So we copy and paste all that say there:
I have seen some tutorials that use Android Studio in this part, which is actually good because you can check in the moment is something is missing. Bad news is that probably will take a few minutes and we don’t want to waste more time right? So just use your favorite editor and edit those files.
Now that have modify everything is time to check all the dependencies of the library
react-native-fbsdk.
Remember when I told you about the buildToolsVersion? Basically we can use the default version or we can change the buildToolsVersion. My recommendation use the same version for everything, you will have less problems, trust me.
If we changing the buildToolsVersion the project won’t compile. Even though we just literally don’t code not a single line. Amazing right!?
But after I little research you see that in the library react-native-fbsdk in the build.gradle you see that everything have to be in the same version, so targetSdk, compileSdkVersion and dependecies compile 'com.android.support:appcompat-v7:25.0.0'
are 25.
Remember that we skip a few steps in the file right!? Well guess what you have to add in the folder Android/build.gradle the following dependency:
buildscript {
repositories {
jcenter()
maven {
url 'https://maven.google.com'
}
}
dependencies {
classpath 'com.android.tools.build:gradle:2.2.3'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
mavenLocal()
jcenter()
maven {
url 'https://maven.google.com'
}
maven {
// All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
url "$rootDir/../node_modules/react-native/android"
}
}
}
maven {
// All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
url "$rootDir/../node_modules/react-native/android"
}
}
}
So if you want to update the version of the buildToolsVersion in the react-native-fbsdk we just need to modify all the version.
So in order to compile the version you just need to use the same compile version for every single library to do so we just need to modify the file android/build.gradle at the end we type this:
afterEvaluate {project ->
if (project.hasProperty("android")) {
android {
compileSdkVersion 27
buildToolsVersion '27.0.2'
}
}
}
}
which save us a looot of time doing that manually. So now we just finally open the project in the app.js file we have this:
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
StyleSheet,
View,
TouchableOpacity,
Text
} from 'react-native';
import { LoginManager } from 'react-native-fbsdk';
export default class App extends Component<{}> {
fbAuth () {
LoginManager.logInWithReadPermissions(['public_profile']).then(function (result) {
if (result.isCancelled) {
console.debug('Login was cancelled!')
} else {
console.debug('Login was successfully on! ' + result.grantedPermissions.toString())
}
}, function (error) {
console.debug('An error ocurred: ' + error)
})
}
render() {
return (
<View style={styles.container}>
<TouchableOpacity onPress={ () => this.fbAuth() }><Text>Hello!</Text></TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
}
});
Now we finally have our login with Facebook. Yaaay! Don’t forget to clap 50 times or more!
#saladtech @augustoalegon
Comentarios
Publicar un comentario