ios – How to properly implement a global User variable in SwiftUI


Im working on my first large scale swiftUI project and don’t know how to properly implement a global variable to store my active user in. In UIKit I could gloabally declare the variable as empty and then load it at runtime. Now with swiftUI I need it to be loaded properly and syntactically correct to show to preview of the UI.

I have a view SignUpView where the new user is created, which is displayed in ContentView like so:

    //State vars
    @State var userNotSignedin = true
    
    var body: some View {
        VinoMainView()
        /**
         when app is opened we must evaluate if a user exists
         if user exists : userNotSignedin = false
         else : userNotSignedIn = true
         */
            .fullScreenCover(isPresented: $userNotSignedin, content: {
                NavigationStack {
                    ZStack {
                        LoginForm()
                        NavigationLink(
                            "Dont Have an Account? Sign-Up Here",
                            destination: SignUpView(userNotSignedin: $userNotSignedin)
                        )
                            .font(.custom("DMSerifDisplay-Regular", size: 15))
                            .padding([.top], 300)
                    }
                }
            })
    }
    
    //check if user exists in privateDB zone
    private func checkIfUserDoesntExists() -> Bool {
        let userDoesntExists = true
        
        return userDoesntExists
    }
}

I’ve tried using different variations of @State vars from various tutorials online and they all make the previews not load so I’m wondering what is the correct way to implement a global var of UserObj in a swiftUI app.

Here is my UserObj class:

public class UserObj: ObservableObject {
    var Fname: String
    var Lname: String
    var username: String
    var password: String
    var email: String
    var phoneNumber: String
    var pfp: UIImage
    var wines: [Wine]
    var recordID: String
    
    init(Fname: String, Lname: String, username: String, password: String, email: String, phoneNumber: String, pfp: UIImage, wines: [Wine], recordID: String = "") {
        self.Fname = Fname
        self.Lname = Lname
        self.username = username
        self.password = password
        self.email = email
        self.phoneNumber = phoneNumber
        self.pfp = pfp
        self.wines = wines
        self.recordID = recordID
    }
    
    init() {
        self.Fname = ""
        self.Lname = ""
        self.username = ""
        self.password = ""
        self.email = ""
        self.phoneNumber = ""
        self.pfp = UIImage()
        self.wines = []
        self.recordID = ""
    }
    
}

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img