Я пытаюсь создать приложение, созданное с помощью React Native, и я использую @react-native-firebase/app": "^17.5.0", "@react-native-firebase/auth": "^17.5.0", "@ react-native-firebase/firestore": "^17.5.0",
Я запускаю приложение с npx react-native run-ios
Мое невежество мешает мне продолжить работу над проектом, который застопорился через несколько дней, так как я пытаюсь зарегистрировать пользователей в Firebase с помощью логики, показанной ниже, файла auth.js, в котором находится аутентификация, и firebase.js, который имеет логику firebase. Это невозможно для меня.
Я несколько раз менял конфигурацию этих файлов, и я не могу добавить сюда все разы, когда я вносил изменения, но их было несколько.
Однако я не могу заставить его зарегистрировать нового пользователя.
Я РЕДАКТИРУЮ ВОПРОС Я РЕДАКТИРУЮ ВОПРОС
Я добавил Podfile по предложению коллеги. Я также должен сказать, что я следовал инструкциям для React Native Firebase, но если я внесу все изменения, предложенные в AppDelegate.m и в Podfile, проект сломается и больше не запустится ни из терминала, ни из Xcode. .
Ошибка относится к следующему файлу:
/node_modules/react-native/Libraries/EventEmitter/NativeEventEmitter.js
Приложение все еще работает, ошибки изменились, но сейчас я записываю следующее:
LOG Running "Cositas enter code here" with {"rootTag":1,"initialProps":{}}
ERROR Invariant Violation: `new NativeEventEmitter()` requires a non-null argument., js engine: hermes
at ?anon_0_ (http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.ApuntesDelCampo:132800:100)
at next (native)
at asyncGeneratorStep (http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.ApuntesDelCampo:20867:26)
at _next (http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.ApuntesDelCampo:20886:29)
at anonymous (http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.ApuntesDelCampo:20891:14)
at tryCallTwo (/Users/distiller/react-native/sdks/hermes/build_iphonesimulator/lib/InternalBytecode/InternalBytecode.js:61:9)
at doResolve (/Users/distiller/react-native/sdks/hermes/build_iphonesimulator/lib/InternalBytecode/InternalBytecode.js:216:25)
at Promise (/Users/distiller/react-native/sdks/hermes/build_iphonesimulator/lib/InternalBytecode/InternalBytecode.js:82:14)
at anonymous (http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.ApuntesDelCampo:20883:25)
at apply (native)
Я понимаю, что причин может быть несколько, поэтому я здесь, так как я не могу найти способ сделать это после многих попыток и многих изменений, которые я сделал, предложенных другими подобными проблемами, найденными в Stackoverflow. Может кто увидит ошибку которая у меня в коде или подскажет правильную настройку.
Я не понимаю, может ли конфигурация iOS влиять на это, всякий раз, когда я запускаю "pod install", все зависимости устанавливаются снова, и он показывает:
[!] The following Swift pods cannot yet be integrated as static libraries:
The Swift pod `FirebaseCoreInternal` depends upon `GoogleUtilities`, which does not define modules. To opt into those targets generating module maps (which is necessary to import them from Swift when building as static libraries), you may set `use_modular_headers!` globally in your Podfile, or specify `:modular_headers => true` for particular dependencies.
Я показываю файлы, и я надеюсь, что вы можете дать мне некоторое представление, чтобы иметь возможность исправить это и двигаться дальше,
============ Подфайл =======
require_relative '../node_modules/react-native/scripts/react_native_pods'
require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'
platform :ios, min_ios_version_supported
prepare_react_native_project!
# If you are using a `react-native-flipper` your iOS build will fail when `NO_FLIPPER=1` is set.
# because `react-native-flipper` depends on (FlipperKit,...) that will be excluded
#
# To fix this you can also exclude `react-native-flipper` using a `react-native.config.js`
# ```js
# module.exports = {
# dependencies: {
# ...(process.env.NO_FLIPPER ? { 'react-native-flipper': { platforms: { ios: null } } } : {}),
# ```
flipper_config = ENV['NO_FLIPPER'] == "1" ? FlipperConfiguration.disabled : FlipperConfiguration.enabled
linkage = ENV['USE_FRAMEWORKS']
if linkage != nil
Pod::UI.puts "Configuring Pod with #{linkage}ally linked Frameworks".green
use_frameworks! :linkage => linkage.to_sym
end
target 'ApuntesDelCampo' do
config = use_native_modules!
# Flags change depending on the env values.
flags = get_default_flags()
use_react_native!(
:path => config[:reactNativePath],
# Hermes is now enabled by default. Disable by setting this flag to false.
# Upcoming versions of React Native may rely on get_default_flags(), but
# we make it explicit here to aid in the React Native upgrade process.
:hermes_enabled => flags[:hermes_enabled],
:fabric_enabled => flags[:fabric_enabled],
# Enables Flipper.
#
# Note that if you have use_frameworks! enabled, Flipper will not work and
# you should disable the next line.
:flipper_configuration => flipper_config,
# An absolute path to your application root.
:app_path => "#{Pod::Config.instance.installation_root}/.."
)
target 'ApuntesDelCampoTests' do
inherit! :complete
# Pods for testing
end
post_install do |installer|
react_native_post_install(
installer,
# Set `mac_catalyst_enabled` to `true` in order to apply patches
# necessary for Mac Catalyst builds
:mac_catalyst_enabled => false
)
__apply_Xcode_12_5_M1_post_install_workaround(installer)
end
end
========. RegisterScreen.js ==================
import React, { useState } from 'react';
import { View, Text, TextInput, TouchableOpacity, Alert } from 'react-native';
import { registerUser } from '../../services/auth'
import styles from './AuthStyles/RegisterScreenStyles'
const RegisterScreen = () => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [username, setUsername] = useState('');
const handleRegister = async () => {
if (email && password && username) {
const { success, error } = await registerUser(email, password, username);
if (success) {
// Registro exitoso
Alert.alert('Registro exitoso', '¡Usuario registrado correctamente!');
} else {
// Error en el registro
Alert.alert('Error de registro', error);
}
} else {
// Validación de campos vacíos
Alert.alert('Campos vacíos', 'Por favor, completa todos los campos.');
}
}
return (
<View style = {styles.container}>
<Text style = {styles.title}>Registro</Text>
<TextInput
style = {styles.input}
placeholder = "Nombre de usuario"
value = {username}
onChangeText = { setUsername}
/>
<TextInput
style = {styles.input}
placeholder = "Correo electrónico"
value = {email}
onChangeText = {setEmail}
/>
<TextInput
style = {styles.input}
placeholder = "Contraseña"
secureTextEntry
value = {password}
onChangeText = {setPassword}
/>
<TouchableOpacity style = {styles.button} onPress = {handleRegister}>
<Text style = {styles.buttonText}>Registrarse</Text>
</TouchableOpacity>
</View>
)
}
export default RegisterScreen;
===========. авторизация.js. ==============
import { firebaseFirestore, firebaseAuth } from "./firebase";
// Registro de usuario
export const registerUser = async (email, password, username) => {
try {
const { user } = await firebaseAuth.createUserWithEmailAndPassword(email, password);
// Almacenar el nombre de usuario en Firestore
await firebaseFirestore.collection('users').doc(user.uid).set({
username,
});
return { success: true, user };
} catch (error) {
return { success: false, error: error.message };
}
};
========. firebase.js. ========
import firebase from '@react-native-firebase/app'
import '@react-native-firebase/firestore'
import '@react-native-firebase/auth'
// Configura Firebase
const firebaseConfig = {
apiKey: "xxxxx",
authDomain: "xxxxx",
projectId: "cxxxxx",
storageBucket: "xxxx",
messagingSenderId: "xxxx",
appId: "xxxxxx"
};
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig)
}
const firebaseFirestore = firebase.firestore();
const firebaseAuth = firebase.auth();
export { firebaseFirestore, firebaseAuth }
Конечно, я уже отредактировал вопрос @user16967562.



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Когда вы запускаете pod install без статической библиотеки, он выдает ошибку и фактически не устанавливает Firebase.
Отключите флиппер, так как флиппер не работает со статической библиотекой:
# Note that if you have use_frameworks! enabled, Flipper will not work if enabled
# :flipper_configuration => flipper_config, <-- comment this line
# An absolute path to your application root
Внутри target 'ApuntesDelCampo' do добавьте два следующих чуть выше flags = ...:
use_frameworks! :linkage => :static
$RNFirebaseAsStaticFramework = true
# Flags change depending on the env values.
flags = get_default_flags()
А также убедитесь, что вы добавили GoogleService-Info.plist в свой проект.
Теперь снова запустите pod install и попробуйте установить приложение.
привет. Я следовал вашим инструкциям, и пока у меня нет ошибок. Но не регистрирует пользователя, приложение показывает баннер, который я показываю на скриншоте, консоль тоже не показывает ошибок. Приложение Firebase '['DEFAULT']' не создано — вызовите firebase.initializeApp(). Я искал решения и, возможно, модифицировал AppDelegate.m , как также объясняется в инструкциях rnfirebase.io, (#import <Firebase.h> //// а также добавлял: [FIRApp configure];) Что вы думаете будь лучше? для этой ошибки? Спасибо ibb.co/7p1Ts24
внесение изменений, которые я предложил @user16967562 , если пользователь зарегистрирован, но не сохранен в коллекции, я думаю, что мне следует изменить код, чтобы сохранить пользователя в firestore или Realtime. Опять больше проблем.
Нет необходимости вызывать firebase.initializeApp(), вы можете просто поставить GoogleService-Info.plist и связать его с целью в xCode, как показано в документации.
Спасибо. это закончилось, но он все еще не регистрирует пользователя: Error Object is not a function
Где именно это происходит? Если это происходит при создании пользователя, замените импорт на import auth from '@react-native-firebase/auth и назовите его так auth().createUserWithEmailAndPassword(email, password).
Еще раз спасибо. Эту проблему я уже исправил, теперь возникла другая. Я не могу войти. Но то, что искал этот вопрос, я решил его по вашему совету, так что ваш ответ будет хорошим. Сейчас попробую исправить проблемы со входом
Можете добавить и свой
Podfile? И это происходит только на iOS, верно?