Я пытаюсь использовать firebase Auth в своем приложении и столкнулся с проблемой при попытке зарегистрировать нового пользователя.
Насколько я могу судить, RN должна автоматически связываться, поэтому мне не нужно вручную Ссылка на это все еще здесь Я
Я прочитал так много возможных ответов на github, документации firebase и ТАК, что я думаю, что я еще больше повернулся и запутался в том, что происходит.
Ниже приведен код, который, по данным моих поисковых запросов в Google, важен для этой проблемы
Любая помощь приветствуется.
Зарегистрируйтесь. js
import React, { useState } from 'react';
import {
StyleSheet,
View,
Image,
Text,
Dimensions,
TouchableHighlight,
ActivityIndicator,
Alert,
TextInput
} from 'react-native';
import { StackActions } from 'react-navigation';
import auth from '@react-native-firebase/auth';
let deviceHeight = Dimensions.get('window').height;
let deviceWidth = Dimensions.get('window').width;
export default function Register({ navigation }) {
const popAction = () => {
navigation.dispatch(StackActions.pop(1));
}
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [c_password, setC_Password] = useState('');
//const [firstName, setFirstName] = useState('');
//const [lastName, setLastName] = useState('');
const [showLoading, setShowLoading] = useState(false);
const register = async() => {
setShowLoading(true);
try {
const doRegister = await auth().createUserWithEmailAndPassword(email, password);
setShowLoading(false);
if(doRegister.user) {
navigation.navigate('Home');
console.log('User registered successfully!')
}
} catch (e) {
setShowLoading(false);
Alert.alert(
e.message
);
}
}
passCheck = () => {
if (password != c_password) {
Alert.alert(
e.message
);
} else {
register()
}
}
return(
<View style={styles.container}>
<View style={styles.topMenu}>
<TouchableHighlight style={styles.back}
activeOpacity={0.6}
underlayColor="#1ABC9C"
onPress={popAction}
>
<Image style={styles.back}
source={require('../../images/icons/back.png')}
/>
</TouchableHighlight>
</View>
<View style={styles.logo}>
<Text style={styles.logoText}>
Register
</Text>
</View>
<View style={styles.registerContainer}>
{/*
<TextInput style={styles.input}
placeholder='First Name'
value={firstName}
onChangeText={setFirstName}
/>
*/}
{/*
<TextInput style={styles.input}
placeholder='Last Name'
value={lastName}
onChangeText={setLastName}
/>
*/}
<TextInput style={styles.input}
placeholder='Your Email'
value={email}
onChangeText={setEmail}
/>
<TextInput style={styles.input}
placeholder='Your Password'
secureTextEntry={true}
value={password}
onChangeText={setPassword}
/>
<TextInput style={styles.input}
placeholder='Confirm Password'
secureTextEntry={true}
value={c_password}
onChangeText={setC_Password}
/>
<TouchableHighlight style={styles.button}
activeOpacity={0.6}
underlayColor="#1ABC9C"
title="Login"
onPress={this.passCheck}
>
<Text>
Register
</Text>
</TouchableHighlight>
</View>
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
backgroundColor: '#1ABC9C'
},
topMenu: {
height: deviceHeight/10,
marginLeft: deviceWidth/30,
marginRight: deviceWidth/30,
justifyContent: 'center'
},
back: {
height: deviceHeight/15,
width: deviceHeight/15,
},
logo: {
height: 2*(deviceHeight/10),
justifyContent: 'center',
alignItems: 'center',
},
logoText: {
color: 'white',
fontStyle: 'italic',
fontWeight: '700',
fontSize: 60
},
registerContainer: {
height: 7*(deviceHeight/10),
alignItems: 'center',
justifyContent: 'space-around',
},
input: {
height: deviceHeight/15,
backgroundColor: 'white',
borderRadius: 50,
alignItems: 'center',
justifyContent: 'center'
},
button:{
height: deviceHeight/15,
backgroundColor: 'white',
borderRadius: 50,
alignItems: 'center',
justifyContent: 'center'
},
buttonText:{
color: '#1ABC9C',
fontStyle: 'italic',
fontWeight: '700',
fontSize: 30
}
});
android / build.gradle:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext {
buildToolsVersion = "28.0.3"
minSdkVersion = 16
compileSdkVersion = 28
targetSdkVersion = 28
}
repositories {
google()
jcenter()
}
dependencies {
classpath("com.android.tools.build:gradle:3.5.2")
classpath("com.google.gms:google-services:4.3.3")
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
mavenLocal()
maven {
// All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
url("$rootDir/../node_modules/react-native/android")
}
maven {
// Android JSC is installed from npm
url("$rootDir/../node_modules/jsc-android/dist")
}
google()
jcenter()
maven { url 'https://www.jitpack.io' }
}
}
android / app / build.gradle:
apply plugin: "com.android.application"
apply plugin: 'base'
import com.android.build.OutputFile
project.ext.react = [
enableHermes: false, // clean and rebuild if changing
]
apply from: "../../node_modules/react-native/react.gradle"
def enableSeparateBuildPerCPUArchitecture = false
def enableProguardInReleaseBuilds = false
def jscFlavor = 'org.webkit:android-jsc:+'
def enableHermes = project.ext.react.get("enableHermes", false);
android {
compileSdkVersion rootProject.ext.compileSdkVersion
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
defaultConfig {
applicationId "com.andrewbrook.nghbrly"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName "1.0"
}
splits {
abi {
reset()
enable enableSeparateBuildPerCPUArchitecture
universalApk false // If true, also generate a universal APK
include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
}
}
signingConfigs {
debug {
storeFile file('debug.keystore')
storePassword 'android'
keyAlias 'androiddebugkey'
keyPassword 'android'
}
}
buildTypes {
debug {
signingConfig signingConfigs.debug
}
release {
// Caution! In production, you need to generate your own keystore file.
// see https://facebook.github.io/react-native/docs/signed-apk-android.
signingConfig signingConfigs.debug
minifyEnabled enableProguardInReleaseBuilds
proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
}
}
packagingOptions {
pickFirst "lib/armeabi-v7a/libc++_shared.so"
pickFirst "lib/arm64-v8a/libc++_shared.so"
pickFirst "lib/x86/libc++_shared.so"
pickFirst "lib/x86_64/libc++_shared.so"
}
// applicationVariants are e.g. debug, release
applicationVariants.all { variant ->
variant.outputs.each { output ->
// For each separate APK per architecture, set a unique version code as described here:
// https://developer.android.com/studio/build/configure-apk-splits.html
def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
def abi = output.getFilter(OutputFile.ABI)
if (abi != null) { // null for the universal-debug, universal-release variants
output.versionCodeOverride =
versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
}
}
}
}
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
//noinspection GradleDynamicVersion
implementation "com.facebook.react:react-native:+" // From node_modules
implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"
debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
exclude group:'com.facebook.fbjni'
}
debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
exclude group:'com.facebook.flipper'
}
debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
exclude group:'com.facebook.flipper'
}
if (enableHermes) {
def hermesPath = "../../node_modules/hermes-engine/android/";
debugImplementation files(hermesPath + "hermes-debug.aar")
releaseImplementation files(hermesPath + "hermes-release.aar")
} else {
implementation jscFlavor
}
}
task copyDownloadableDepsToLibs(type: Copy) {
from configurations.compile
into 'libs'
}
apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
apply plugin: 'com.google.gms.google-services'
settings.gradle:
rootProject.name = 'nghbrly'
apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings)
include ':app'
include ':@react-native-firebase_app'
project(':@react-native-firebase_app').projectDir = new File(rootProject.projectDir, './../node_modules/@react-native-firebase/app/android')
Главное приложение. java:
package com.nghbrly;
import android.app.Application;
import android.content.Context;
import com.facebook.react.PackageList;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.soloader.SoLoader;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import com.facebook.react.BuildConfig;
import io.invertase.firebase.app.RNFirebaseAppPackage;
import io.invertase.firebase.auth.RNFirebaseAuthPackage;
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost =
new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
@SuppressWarnings("UnnecessaryLocalVariable")
List<ReactPackage> packages = new PackageList(this).getPackages();
// Packages that cannot be autolinked yet can be added manually here, for example:
// packages.add(new MyReactNativePackage());
packages.add(new RNFirebaseAppPackage());
packages.add(new RNFirebaseAuthPackage());
return packages;
}
@Override
protected String getJSMainModuleName() {
return "index";
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
@Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
}
/**
* Loads Flipper in React Native templates. Call this in the onCreate method with something like
* initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
*
* @param context
* @param reactInstanceManager
*/
private static void initializeFlipper(
Context context, ReactInstanceManager reactInstanceManager) {
if (BuildConfig.DEBUG) {
try {
/*
We use reflection here to pick up the class that initializes Flipper,
since Flipper library is not available in release mode
*/
Class<?> aClass = Class.forName("com.nghbrly.ReactNativeFlipper");
aClass
.getMethod("initializeFlipper", Context.class, ReactInstanceManager.class)
.invoke(null, context, reactInstanceManager);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}