SwiftUI Firebase List and Add
ContentView.swift
//
// ContentView.swift
// DevSwiftUI
//
// Created by Cairocoders
//
import SwiftUI
struct ContentView: View {
@State private var name: String = ""
@ObservedObject private var viewModel = ContactViewModel()
var body: some View {
NavigationView {
VStack { //vertical stack
HStack { //Horizontal Stack
TextField("Add New...", text: $name)
.textFieldStyle(RoundedBorderTextFieldStyle())
.font(.title)
Button(action: {
self.viewModel.addData(name: name)
print("button tapped!")
}) {
Image(systemName: "plus")
.padding()
.foregroundColor(.white)
.background(Color.blue)
.cornerRadius(40)
}
.padding(.leading, 5)
}.padding() //end horizontal stack
List(viewModel.contacts) { contact in
VStack(alignment: .leading) {
Text(contact.name).font(.title)
}
}.onAppear() {
self.viewModel.fetchData()
}
}
.navigationTitle("Contact List")
}
}// End body
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Contact.swift
//
// Contact.swift
// DevSwiftUI
//
// Created by Cairocoders
//
import Foundation
import SwiftUI
struct Contact: Codable, Identifiable {
var id: String = UUID().uuidString
var name: String
}
ContactViewModel.swift
//
// ContactViewModel.swift
// DevSwiftUI
//
// Created by Cairocoders
//
import Foundation
import FirebaseFirestore
import SwiftUI
class ContactViewModel: ObservableObject {
@Published var contacts = [Contact]()
private var db = Firestore.firestore()
func fetchData() {
db.collection("contacts").addSnapshotListener { (querySnapshot, error) in
guard let documents = querySnapshot?.documents else {
print("No documents")
return
}
self.contacts = documents.map { (queryDocumentSnapshot) -> Contact in
let data = queryDocumentSnapshot.data()
let name = data["name"] as? String ?? ""
return Contact(name: name)
}
}
}
func addData(name: String) {
db.collection("contacts").addDocument(data: ["name": name])
}
}
DevSwiftUIApp.swift
//
// DevSwiftUIApp.swift
// DevSwiftUI
//
// Created by Cairocoders
//
import SwiftUI
import Firebase
@main
struct DevSwiftUIApp: App {
init() {
FirebaseApp.configure()
}
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
VIDEO