article

Sunday, October 17, 2021

SwiftUI Firebase Simple Contact List

SwiftUI Firebase Simple Contact List In this tutorial I will show how Add document and fetch documents

ContentView.swift
 
//
//  ContentView.swift
//  DevSwiftUI
//
//  Created by Cairocoders
//

import SwiftUI
import Firebase

struct ContentView: View {
    
    @ObservedObject private var viewModel = ContactViewModel()

    @State private var showModal = false
    
    var body: some View {
        NavigationView {
            List() {
                ForEach(viewModel.contacts) { contact in
                    VStack(alignment: .leading) {
                        Text(contact.name ?? "").font(.title)
                    }
                }
            }.onAppear() {
                self.viewModel.fetchData()
            }
            .navigationTitle("Contact List")
            .navigationBarItems(trailing:
                Button(action: {
                    self.showModal = true
                }) {
                    VStack {
                        Image(systemName: "plus")
                            .resizable()
                            .scaledToFit()
                            .frame(width: 32, height: 32, alignment: .center)
                            .foregroundColor(.green)
                    }
                }
                .sheet(isPresented: self.$showModal, onDismiss: {  }) {
                    AddView(showModal: self.$showModal)
                })
            .navigationBarTitle(Text("Add New"), displayMode: .inline)

        }
    }
    
}
 
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
ContactViewModel.swift
 
//
//  ContactViewModel.swift
//  DevSwiftUI
//
//  Created by Cairocoders
//

import Foundation
import FirebaseFirestore
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]) { error in
            if let error = error {
                print(error.localizedDescription)
            }
        }
    }

}
Contact.swift
 
//
//  Contact.swift
//  DevSwiftUI
//
//  Created by Cairocoders
//

import SwiftUI
import FirebaseFirestoreSwift

struct Contact: Codable, Identifiable {
    var id: String = UUID().uuidString
    var name: String?
}
AddView.swift
 
//
//  AddView.swift
//  DevSwiftUI
//
//  Created by Cairocoders
//

import SwiftUI

struct AddView: View {
    
    @Binding var showModal: Bool
    @State private var name: String = ""
    @ObservedObject private var viewModel = ContactViewModel()
    
    var body: some View {
        NavigationView {
            Form {
              Section(header: Text("Name")) {
                  TextField("Enter your name", text: $name)
              }
              Section() {
                  Button(action: {
                      self.viewModel.addData(name: name)
                      self.showModal.toggle()
                  }) {
                      HStack {
                          Text("Add New")
                              .font(.title)
                      }
                  .padding()
                  .foregroundColor(.white)
                  .background(Color.blue)
                  .cornerRadius(30)
                  }
               }
            }
            .navigationTitle("New Contact")
        }
    }
}
DevSwiftUIApp.swift
 
//
//  DevSwiftUIApp.swift
//  DevSwiftUI
//
//  Created by Cairocoders
//

import SwiftUI
import Firebase

@main
struct DevSwiftUIApp: App {
     
    @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
    
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

class AppDelegate: NSObject,UIApplicationDelegate{
      
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
          
        FirebaseApp.configure()
        return true
    }
}

Related Post