Snippets Collections
Client Side Code Test.jsx --
import React, { useState, useEffect, useRef } from 'react';
import { initializeApp } from 'firebase/app';
import { getAuth, RecaptchaVerifier, signInWithPhoneNumber } from 'firebase/auth';

// Firebase config - replace with your own config
const firebaseConfig = {
  apiKey: "AIzaSyCb9uireOMfRCFfJpWWr1WmKdP629rNcCk",
  authDomain: "trial-34ed7.firebaseapp.com",
  projectId: "trial-34ed7",
  storageBucket: "trial-34ed7.appspot.com",
  messagingSenderId: "71628620493",
  appId: "1:71628620493:web:7c44729da8f9c541e55f84",
  measurementId: "G-N9GPF8ZQMZ"
};

// Initialize Firebase App
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);

function Test() {
  const [mobile, setMobile] = useState('');
  const [otp, setOtp] = useState('');
  let confirmationResult = useRef(null);

  useEffect(() => {
    configureCaptcha();
  }, []);

  const handleChange = (e) => {
    const { name, value } = e.target;
    if (name === 'mobile') {
      setMobile(value);
    } else if (name === 'otp') {
      setOtp(value);
    }
  };

  const configureCaptcha = () => {
    window.recaptchaVerifier = new RecaptchaVerifier(auth, 'sign-in-button', {
      'size': 'invisible',
      'callback': (response) => {
        // reCAPTCHA solved, allow signInWithPhoneNumber.
        onSignInSubmit();
      }
    }, auth);
  };

  const onSignInSubmit = async (e) => {
    e.preventDefault();
    const phoneNumber = "+91" + mobile;
    console.log(phoneNumber);
    const appVerifier = window.recaptchaVerifier;
    try {
      confirmationResult.current = await signInWithPhoneNumber(auth, phoneNumber, appVerifier);
      console.log("OTP has been sent");
    } catch (error) {
      console.error("SMS not sent", error);
    }
  };

  const onSubmitOTP = async (e) => {
    e.preventDefault();
    try {
      const result = await confirmationResult.current.confirm(otp);
      const user = result.user;
      console.log(JSON.stringify(user));
      alert("User is verified");
    } catch (error) {
      console.error("User couldn't sign in (bad verification code?)", error);
    }
  };

  return (
    <div>
      <h2>Login Form</h2>
      <form onSubmit={onSignInSubmit}>
        <div id="sign-in-button"></div>
        <input type="text" name="mobile" placeholder="Mobile number" required onChange={handleChange} />
        <button type="submit">Submit</button>
      </form>

      <h2>Enter OTP</h2>
      <form onSubmit={onSubmitOTP}>
        <input type="text" name="otp" placeholder="OTP Number" required onChange={handleChange} />
        <button type="submit">Submit</button>
      </form>
    </div>
  );
}

export default Test;




<html>
<head>
</head>
<body>
<div>
<a href="https://www.amazon.de/dp/B0BY49J5J3/?tag=r29future">E-Book</a></div>
</body>
</html>
import SwiftUI

// Capítulo 5: Casos de Uso Avanzados de Property Wrappers en SwiftUI.
// Ejemplo: Combinando diferentes Property Wrappers...

class UserData: ObservableObject {
    @Published var name: String = "John Doe"
}

@propertyWrapper
struct UpperCase {
    private(set) var value: String
    
    var wrappedValue: String {
        get { value }
        set { value = newValue.uppercased() }
    }
    
    init(wrappedValue: String) {
        self.value = wrappedValue.uppercased()
    }
}

struct User {
    @UpperCase var name: String
}

struct UserView: View {
    @ObservedObject var userData: UserData
    
    var body: some View {
        VStack {
            Text("Hello, \(userData.name)")
            TextField("Enter your name", text: $userData.name)
        }
    }
}

struct ContentView: View {
    @ObservedObject var userData = UserData()
    @State var user = User(name: "John Doe")
    
    var body: some View {
        VStack {
            UserView(userData: userData)
            Text("Hello, \(user.name)")
            TextField("Enter your name", text: $user.name)
        }
    }
}
import SwiftUI

// Capítulo 4: Creando nuestros propios Property Wrappers

@propertyWrapper
struct UpperCase {
    private(set) var value: String
    
    var wrappedValue: String {
        get { value }
        set { value = newValue.uppercased() }
    }
    
    init(wrappedValue: String) {
        self.value = wrappedValue.uppercased()
    }
}

struct User {
    @UpperCase var name: String
}

struct UserView: View {
    @ObservedObject var user: User
    
    var body: some View {
        VStack {
            Text("Hello, \(user.name)")
            TextField("Enter your name", text: $user.name)
        }
    }
}

struct ContentView: View {
     var body: some View {
       UserView(user: User(name: "John Doe"))
     }
}
import SwiftUI

class UserData: ObservableObject {
    @Published var name: String = "John Doe"
}

struct UserView: View {
    @ObservedObject var userData: UserData
    
    var body: some View {
        VStack {
            Text("Hello, \(userData.name)")
            TextField("Enter your name", text: $userData.name)
        }
    }
}

struct ContentView: View {
    var body: some View {
        UserView(userData: UserData())
    }
}
import SwiftUI

class UserData: ObservableObject {
    @Published var name: String = "John Doe"
}

struct UserView: View {
    @StateObject var userData: UserData
    
    var body: some View {
        VStack {
            Text("Hello, \(userData.name)")
            TextField("Enter your name", text: $userData.name)
        }
    }
}

struct ContentView: View {
    var body: some View {
        UserView(userData: UserData())
    }
}
import SwiftUI

struct UserSettings {
    var fontSize: CGFloat = 17
}

struct UserView: View {
    @EnvironmentObject var userSettings: UserSettings
    
    var body: some View {
        VStack {
            Text("Hello, World")
                .font(.system(size: userSettings.fontSize))
            Slider(value: $userSettings.fontSize, in: 10...30)
        }
    }
}

struct ContentView: View {
    var body: some View {
        UserView().environmentObject(UserSettings())
    }
}
import SwiftUI

struct User {
    var name: String
}

struct UserView: View {
    @Binding var user: User
    
    var body: some View {
        VStack {
            Text("Hello, \(user.name)")
            TextField("Enter your name", text: $user.name)
        }
    }
}

struct ContentView: View {
    @State var user = User(name: "John Doe")
    
    var body: some View {
        UserView(user: $user)
    }
}
import SwiftUI

struct ContentView: View {
    @State var name: String = "John Doe"
    
    var body: some View {
        VStack {
            Text("Hello, \(name)")
            TextField("Enter your name", text: $name)
        }
    }
}
//7. Implementar la autenticación de Firebase en nuestra aplicación

//Para implementar la autenticación de Firebase en nuestra aplicación, debemos seguir los siguientes pasos:

//- Agregar la autenticación de Firebase a nuestra aplicación.
//- Crear una cuenta de usuario y permitir que los usuarios inicien sesión y cierren sesión en la aplicación.

//```swiftui
// Registrar un usuario
Auth.auth().createUser(withEmail: email, password: password) { (authResult, error) in
  if let error = error {
    print("Error al registrar el usuario: \(error.localizedDescription)")
    return
  }
  guard let user = authResult?.user else {
    print("No se pudo obtener el usuario")
    return
  }
  print("Usuario registrado con éxito")
}

// Iniciar sesión con un usuario existente
Auth.auth().signIn(withEmail: email, password: password) { (authResult, error) in
  if let error = error {
    print("Error al iniciar sesión: \(error.localizedDescription)")
    return
  }
  guard let user = authResult?.user else {
    print("No se pudo obtener el usuario")
    return
  }
  print("Inicio de sesión exitoso")
}

// Cerrar sesión
do {
  try Auth.auth().signOut()
  print("Cierre de sesión exitoso")
} catch let error as NSError {
  print("Error al cerrar sesión: \(error.localizedDescription)")
}
//6. Implementar Cloud Storage en nuestra aplicación

//Para implementar Cloud Storage en nuestra aplicación, debemos seguir los siguientes pasos:

//- Agregar Cloud Storage a nuestra aplicación.
//- Subir y descargar archivos desde el almacenamiento en la nube.

//```swift
// Subir un archivo al almacenamiento en la nube
let storage = Storage.storage()
let storageRef = storage.reference()
let imageRef = storageRef.child("images/\(imageName)")
let metadata = StorageMetadata()
metadata.contentType = "image/jpeg"
let imageData = UIImageJPEGRepresentation(image, 0.8)!
imageRef.putData(imageData, metadata: metadata) { (metadata, error) in
  if let error = error {
    print("Error al subir el archivo: \(error.localizedDescription)")
    return
  }
  print("Archivo subido con éxito")
}

// Descargar un archivo desde el almacenamiento en la nube
let storage = Storage.storage()
let storageRef = storage.reference()
let imageRef = storageRef.child("images/\(imageName)")
imageRef.getData(maxSize: 1 * 1024 * 1024) { (data, error) in
  if let error = error {
    print("Error al descargar el archivo: \(error.localizedDescription)")
    return
  }
  guard let imageData = data else {
    print("No se pudo obtener el archivo")
    return
  }
  let image = UIImage(data: imageData)
  print("Archivo descargado con éxito")
}
// Leer datos de la base de datos
let db = Firestore.firestore()
db.collection("users").document(userId).getDocument { (document, error) in
if let document = document, document.exists {
let data = document.data()
let name = data?["name"] as? String ?? ""
let email = data?["email"] as? String ?? ""
print("Nombre: (name), Email: (email)")
} else {
print("El documento no existe")
}
}

// Consultar datos de la base de datos
let db = Firestore.firestore()
db.collection("users").whereField("name", isEqualTo: "Juan Pérez").getDocuments { (querySnapshot, error) in
  if let error = error {
         print("Error al consultar los datos: (error.localizedDescription)")
      return
}
guard let documents = querySnapshot?.documents else {
      print("No se encontraron documentos")
      return
}
for document in documents {
let data = document.data()
let name = data["name"] as? String ?? ""
let email = data["email"] as? String ?? ""
     print("Nombre: (name), Email: (email)")
  }
}

// Escuchar cambios en la base de datos
let db = Firestore.firestore()
db.collection("users").document(userId).addSnapshotListener { (document, error) in
  if let document = document, document.exists {
let data = document.data()
let name = data?["name"] as? String ?? ""
let email = data?["email"] as? String ?? ""
      print("Nombre: (name), Email: (email)")
} else {
     print("El documento no existe")
}
}
// Importar Firebase Auth
import Firebase
import FirebaseAuth

// Registrar un usuario
Auth.auth().createUser(withEmail: email, password: password) { (result, error) in
  if let error = error {
    print("Error al registrar el usuario: \(error.localizedDescription)")
    return
  }
  guard let user = result?.user else {
    print("No se pudo obtener el usuario")
    return
  }
  print("Usuario registrado con éxito: \(user.uid)")
}

// Autenticar un usuario
Auth.auth().signIn(withEmail: email, password: password) { (result, error) in
  if let error = error {
    print("Error al autenticar el usuario: \(error.localizedDescription)")
    return
  }
  guard let user = result?.user else {
    print("No se pudo obtener el usuario")
    return
  }
  print("Usuario autenticado con éxito: \(user.uid)")
}
//Para eliminar datos de la base de datos, podemos utilizar el siguiente código:
let documentRef = db.collection("cities").document("SF")
documentRef.delete() { error in
  if let error = error {
    print("Error al eliminar documento: \(error.localizedDescription)")
    return
  }
  print("Documento eliminado con éxito")
}
//Para actualizar datos en la base de datos, podemos utilizar el siguiente código:
let documentRef = db.collection("cities").document("SF")
documentRef.updateData([
  "population": 884363,
  "capital": false
]) { error in
  if let error = error {
    print("Error al actualizar datos: \(error.localizedDescription)")
    return
  }
  print("Datos actualizados con éxito")
}
//Para escribir datos en la base de datos, podemos utilizar el siguiente código:
let data: [String: Any] = [
  "name": "Santo Domingo",
  "population": 13929286
]
db.collection("cities").document("San Dom").setData(data) { error in
  if let error = error {
    print("Error al escribir datos: \(error.localizedDescription)")
    return
  }
  print("Datos escritos con éxito")
}
//Para leer datos de la base de datos, podemos utilizar los siguientes métodos:

// Leer todos los documentos de una colección
db.collection("cities").getDocuments() { (querySnapshot, error) in
  if let error = error {
    print("Error al obtener documentos: \(error.localizedDescription)")
    return
  }
  for document in querySnapshot!.documents {
    let data = document.data()
    let name = data["name"] as? String ?? ""
    let population = data["population"] as? Int ?? 0
    print("Ciudad: \(name), Población: \(population)")
  }
}

// Leer un documento específico de una colección
db.collection("cities").document("SF").getDocument() { (document, error) in
  if let document = document, document.exists {
    let data = document.data()
    let name = data?["name"] as? String ?? ""
    let population = data?["population"] as? Int ?? 0
    print("Ciudad: \(name), Población: \(population)")
  } else {
    print("El documento no existe")
  }
}
//Para crear una referencia a la base de datos, podemos utilizar el siguiente código:
let db = Firestore.firestore()
//Para eliminar archivos, podemos utilizar el siguiente código:
let fileRef = storageRef.child("files").child("fileName")
fileRef.delete { (error) in
  if let error = error {
    print("Error al eliminar archivo: \(error.localizedDescription)")
    return
  }
  print("Archivo eliminado con éxito")
}
//Para cargar y descargar archivos, podemos utilizar los siguientes métodos:

// Cargar un archivo
let data = Data()
let fileRef = storageRef.child("files").child("fileName")
fileRef.putData(data, metadata: nil) { (metadata, error) in
  if let error = error {
    print("Error al cargar archivo: \(error.localizedDescription)")
    return
  }
  print("Archivo cargado con éxito")
}

// Descargar un archivo
let fileRef = storageRef.child("files").child("fileName")
fileRef.getData(maxSize: 10 * 1024 * 1024) { (data, error) in
  if let error = error {
    print("Error al descargar archivo: \(error.localizedDescription)")
    return
  }
  print("Archivo descargado con éxito")
}
//Para crear una referencia al almacenamiento, podemos utilizar el siguiente código:
let storageRef = Storage.storage().reference()
if let user = Auth.auth().currentUser {
  let email = user.email
  let uid = user.uid
  print("Email: \(email), UID: \(uid)")
}
Auth.auth().signIn(with: credential) { (result, error) in
  if let error = error {
    print("Error al autenticar usuario: \(error.localizedDescription)")
    return
  }
  print("Usuario autenticado con éxito")
}
Auth.auth().signIn(with: credential) { (result, error) in
  if let error = error {
    print("Error al autenticar usuario: \(error.localizedDescription)")
    return
  }
  print("Usuario autenticado con éxito")
}
let provider = OAuthProvider(providerID: "google.com")
provider.scopes = ["email", "profile"]
ref.child("users").child("userId").observe(.value) { (snapshot) in
  if let value = snapshot.value as? [String: Any] {
    let name = value["name"] as? String ?? ""
    let age = value["age"] as? Int ?? 0
    print("Name: \(name), Age: \(age)")
  }
}
// Escribir datos
ref.child("users").child("userId").setValue(["name": "John", "age": 30])

// Leer datos
ref.child("users").child("userId").observeSingleEvent(of: .value) { (snapshot) in
  if let value = snapshot.value as? [String: Any] {
    let name = value["name"] as? String ?? ""
    let age = value["age"] as? Int ?? 0
    print("Name: \(name), Age: \(age)")
  }
}
  private fun downloadfile(
        filUrl: String,
        filePath: String,
        completion: (response: String) -> Unit
    ) {

        binding.progressBar.max = 100
        binding.progressBar.setProgress(0)
        binding.progressTextView.setText("0")

        val storage = FirebaseStorage.getInstance()
        val storageRef =
            storage.getReferenceFromUrl(filUrl)

        val localFile = File(filePath)

        storageRef.getFile(localFile)
            .addOnProgressListener {
                Log.e(TAG, "downloadfile: " + it.bytesTransferred + "/" + it.totalByteCount)
                if (it.totalByteCount.toInt() != -1) {
                    val progress: Double = 100.0 * it.bytesTransferred / it.totalByteCount
                    binding.progressBar.setProgress(progress.toInt())
                    binding.progressTextView.setText(progress.toInt().toString())
                }

            }
            .addOnSuccessListener(object : OnSuccessListener<FileDownloadTask.TaskSnapshot?> {
                override fun onSuccess(taskSnapshot: FileDownloadTask.TaskSnapshot?) {
                    Log.e(
                        TAG,
                        "downloadfile:onSuccess: ;local tem file created  created $localFile"
                    )
                    completion("1")
                }
            }).addOnFailureListener(object : OnFailureListener {
                override fun onFailure(@NonNull exception: java.lang.Exception) {
                    Log.e(
                        TAG,
                        "downloadfile:onFailure: ;local tem file not created  created $exception"
                    )
                    completion("downloadfile:onFailure: ;local tem file not created  created $exception")
                }
            })
    }
const provider = new this.$fireModule.auth.GoogleAuthProvider()
this.$fire.auth
	.signInWithPopup(provider)
	.catch((error) => alert(error))
	.then((data) => console.log(data.user, data.credential.accessToken))
$fire.auth().signInWithEmailAndPassword(email, password)
star

Sun Mar 31 2024 21:26:48 GMT+0000 (Coordinated Universal Time) https://www.youtube.com/watch?v=lDzBtOo1S8Y

#firebase #reactjs #mern #mobileotp #verification
star

Sun Jun 20 2021 17:28:44 GMT+0000 (Coordinated Universal Time)

#firebase
star

Sun Jun 20 2021 17:04:19 GMT+0000 (Coordinated Universal Time)

#firebase

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension