I have an app where the user must enter a "pincode" to enter the main user page. I am storing this code in a firebase database. If the user enters the right code it should log them in. Here is how I am handling it:
So when the user clicks on SignIn
it calls a function func signIn(password: String)
I pass it a value from the user input. And here is how I am validating it from firebase:
func signIn(password: String){
taskRef = Database.database().reference(withPath: "PinCodes")
taskRef?.observeSingleEvent(of: .value, with: { (snapshot) in
if let codeDict = (snapshot.value as? [String:String]){
self.pass = codeDict["Code"]!
if(self.pass == password){
NavigationLink(destination: OpenSky()){
Text("Welcome")
}
}else{
closeSky()
}
}
})
}
My goal is that when the user enters the right code and hits login, it should navigate them to a welcome screen. As you can see, I tried to do that with NavigationLink
however, it doesn't work. It gives me a warning: "result of 'NavigationLink<Label, Destination>' initializer is unused
"
How can I get this to work so that it opens up the UserScreen if they enter the right code in?
CodePudding user response:
Yeah I was facing a similar problem. I had to check if a username existed in my database and then proceed to show the next screen. The problem with the navigationLink was when I click it, it would just go to the next screen without any validation. Here is what helped me.
struct View1: View {
@State var shouldShowNextScreen: Bool = false
var body: some View {
NavigationView {
ZStack {
Color.red
NavigationLink(isActive: $shouldShowNextScreen, destination: { View2() }) {
Button {
//Here you can do the validation <-----
if password == passwordFromDatabase {
shouldShowNextScreen = true
}
} label: {
Text("Log In")
.frame(maxWidth: .infinity, minHeight: 44)
.background(.white)
.cornerRadius(8)
.padding()
}
}
}
}
}
}
CodePudding user response:
Here is your solution: if your var isShowingDetailView is a @State, your view will be updated whenever your vas is updated.
add isActive param on your NavigationLink, pass the var to true when your signIn is ok, and it will works
struct ContentView: View {
@State private var isShowingDetailView = false
var body: some View {
NavigationView {
VStack {
NavigationLink(destination: Text("Second View"), isActive: $isShowingDetailView) { EmptyView() }
Button("Tap to show detail") {
isShowingDetailView = true
}
}
.navigationTitle("Navigation")
}
}
}