NEW: Learn to build amazing SwiftUI apps for macOS with my new book! >>

I have an error and I need help with it. Firebase and Swift UI

Forums > SwiftUI

Hey y'all.

I have an error that is popping up when I go run the app. The error states:

Thread 1: Fatal error: No ObservableObject of type AccountCreationViewModel found. A View.environmentObject(_:) for AccountCreationViewModel may be missing as an ancestor of this view.

This is the file that the error come in:

import SwiftUI

struct RegisterView: View {

    @EnvironmentObject var accountCreation: AccountCreationViewModel

    init() {
        UITextView.appearance().backgroundColor = .clear
    }

    var body: some View {
        VStack {
            Image("SMK")
                .resizable()
                .aspectRatio(contentMode: .fit)
                .frame(height: UIScreen.main.bounds.height / 3.5)
                .cornerRadius(100)
                .padding(.top, 50)

            ZStack{

                if accountCreation.pageNumber == 0{
                    SignView()
                        .environmentObject(AccountCreationViewModel())

                }

               else if accountCreation.pageNumber == 1{
                    Register()
                        .transition(.move(edge: .trailing))
                }
               else {
                ImageRegister()
               }

            }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .background(Color.white).ignoresSafeArea(.all, edges: .bottom)
            .clipShape(CustomCorners(corners: [.topLeft, .topRight]))
        }
        .background(Color(red: 22/255, green: 22/255, blue: 24/255))
        .ignoresSafeArea(.all, edges: .all)
        .alert(isPresented: $accountCreation.alert, content: {
            Alert(title: Text("Error"), message: Text(accountCreation.alertMsg), dismissButton: .default(Text("Ok")))
        })

    }
}

struct RegisterView_Previews: PreviewProvider {
    static var previews: some View {
        RegisterView()
            .environmentObject(AccountCreationViewModel())
    }
}

This is the data model:

import SwiftUI
import Firebase
import CoreLocation

class AccountCreationViewModel: NSObject,ObservableObject, CLLocationManagerDelegate {

    @Published var name  = ""
    @Published var location  = ""
    @Published var age = ""

    @Published var phNumber  = ""
    @Published var code  = ""

    @Published var pageNumber = 0

    @Published var images = Array(repeating: Data(count: 0), count: 4)
    @Published var picker = false

    @Published var alert = false
    @Published var alertMsg = ""

    @Published var isLoading = false

    @Published var CODE = ""

    @AppStorage ("log_Status") var status = false

    func login(){

        Auth.auth().settings?.isAppVerificationDisabledForTesting = true

        isLoading.toggle()

        PhoneAuthProvider.provider().verifyPhoneNumber("+" + code + phNumber, uiDelegate: nil) { (CODE,err) in

            if err != nil {
                self.alertMsg = err!.localizedDescription
                self.alert.toggle()
                return
            }
            self.CODE = CODE!

            let alertView = UIAlertController(title: "Verification", message: "Please enter your OTP", preferredStyle: .alert)

            let cancel = UIAlertAction(title: "Cancel", style: .destructive, handler: nil)

            let ok = UIAlertAction(title: "OK", style: .default) { (_) in

                if let otp = alertView.textFields![0].text{
                    let credentials = PhoneAuthProvider.provider().credential(withVerificationID: self.CODE, verificationCode: otp)

                    self.isLoading.toggle()

                    Auth.auth().signIn(with: credentials) { (res, err) in

                        self.isLoading.toggle()

                        if err != nil {
                            self.alertMsg = err!.localizedDescription
                            self.alert.toggle()
                            return
                        }
                        withAnimation(){
                            self.pageNumber = 1
                        }
                    }
                }

            }
            alertView.addTextField() { (txt) in
                txt.placeholder = "4860"

            }
            alertView.addAction(cancel)
            alertView.addAction(ok)

            UIApplication.shared.windows.first?.rootViewController?.present(alertView, animated: true, completion: nil)
        }

    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let last = locations.last!
        CLGeocoder().reverseGeocodeLocation(last) { (places, _)
            in guard let placeMarks = places else{return}
            self.location = (placeMarks.first?.name ?? "") + ", " + (placeMarks.first?.locality ?? "")

        }

    }

    func signUp(){
        let storage = Storage.storage().reference()

        let ref = storage.child("profile_Pics").child(Auth.auth().currentUser!.uid)

        var urls : [String] = []
        isLoading.toggle()

        for index in images.indices{
            ref.child("img\(index)").putData(images[index], metadata: nil) {
                (_, err) in if err != nil{
                    self.alertMsg = err!.localizedDescription
                    self.alert.toggle()
                    self.isLoading.toggle()
                    return

                }
                ref.child("img\(index)").downloadURL {(url, _) in

                    guard let imageUrl = url else{return}

                    urls.append("\(imageUrl)")

                    if urls.count ==

                    self.images.count{

                    self.RegisterUser(urls: urls)

                    }
                }
            }
        }
    }

    func RegisterUser(urls: [String]){
        let db = Firestore.firestore()
        db.collection("Users").document(Auth.auth().currentUser!.uid).setData([

        "userName": self.name,
        "location": self.location,
        "age": self.age,
        "imageUrls": urls

        ]) { (err) in

            self.isLoading.toggle()
            if err != nil{
                self.alertMsg = err!.localizedDescription
                self.alert.toggle()
                return

            }
            self.status = true
        }
    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {

    }
    func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) { if manager.authorizationStatus == .authorizedWhenInUse{ manager.requestLocation()

        }
    }
}

Since this is my first time using Firebase, it is hard for me to debug it. Can you please help me?

1      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Spend less time managing in-app purchase infrastructure so you can focus on building your app. RevenueCat gives everything you need to easily implement, manage, and analyze in-app purchases and subscriptions without managing servers or writing backend code.

Get Started

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.