Contenidos
Configurar un proyecto en Firebase
Para insertar o leer en la base de datos es necesario configurar las reglas en Firestore
1 2 3 4 5 6 7 8 9 |
rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { match /{document=**} { allow read, write: if true; } } } |
Crear un programa en Xcode que inserte un registro en la base de datos y lea los registros que hay en la base de datos
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
import SwiftUI import Firebase import FirebaseFirestore class AppDelegate: NSObject, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool { FirebaseApp.configure() return true } } struct ContentView: View { var body: some View { VStack { Button(action: { insertyreadDataToFirebase() }) { Text("Agregar valor a Firebase") .padding() .foregroundColor(.white) .background(Color.blue) .cornerRadius(8) } } } func insertyreadDataToFirebase() { // Reference to Firestore let db = Firestore.firestore() db.collection("datos").addDocument(data: [ "title": "kk2", ]) db.collection("datos").getDocuments { (snapshot, error) in if let snapshot = snapshot { for document in snapshot.documents { let title = document.data()["nombre"] as? String print(title) } } } } } @main struct YourApp: App { // Register app delegate for Firebase setup @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate var body: some Scene { WindowGroup { NavigationView { ContentView() } } } } |
Posibles errores
Permisos
1 2 3 4 5 6 7 |
10.19.1 - [FirebaseFirestore][I-FST000001] Listen for query at datos failed: Missing or insufficient permissions. 10.19.1 - [FirebaseFirestore][I-FST000001] WriteStream (106f04248) Stream error: 'Permission denied: Missing or insufficient permissions.' 10.19.1 - [FirebaseFirestore][I-FST000001] Write at datos/afasfasfasdf failed: Missing or insufficient permissions. 10.19.1 - [FirebaseFirestore][I-FST000001] WatchStream (106d041d8) Stream error: 'Cancelled: Disconnecting idle stream. Timed out waiting for new targets.' |
Las solución es cambiar a true el permiso de read y write.