import SwiftUI
import FirebaseAuth
struct LoginScreen: View {
@State private var email = ""
@State private var password = ""
@State private var errorMessage = ""
@State private var isLoading = false
var body: some View {
VStack(spacing: 20) {
Text("Login Screen")
.font(.largeTitle)
.bold()
TextField("Email", text: $email)
.keyboardType(.emailAddress)
.autocapitalization(.none)
.padding()
.background(Color(UIColor.secondarySystemBackground))
.cornerRadius(8)
SecureField("Password", text: $password)
.padding()
.background(Color(UIColor.secondarySystemBackground))
.cornerRadius(8)
Button(action: {
loginUser()
}) {
if isLoading {
ProgressView()
.frame(maxWidth: .infinity)
.padding()
} else {
Text("Login")
.frame(maxWidth: .infinity)
.padding()
}
}
.background(isLoading ? Color.gray : Color.blue)
.foregroundColor(.white)
.cornerRadius(8)
.disabled(isLoading)
if !errorMessage.isEmpty {
Text(errorMessage)
.foregroundColor(.red)
.multilineTextAlignment(.center)
}
Spacer()
}
.padding()
}
private func loginUser() {
errorMessage = ""
isLoading = true
Auth.auth().signIn(withEmail: email, password: password) { result, error in
isLoading = false
if let error = error {
errorMessage = error.localizedDescription
} else {
errorMessage = ""
// Successful login - proceed to next screen or update UI
}
}
}
}
struct LoginScreen_Previews: PreviewProvider {
static var previews: some View {
LoginScreen()
}
}
This solution uses SwiftUI to build a simple login screen. It has two input fields: one for email and one for password. The password field hides the text for privacy.
The Login button triggers the loginUser() function, which uses Firebase Authentication's signIn(withEmail:password:) method to attempt login.
While the login is in progress, the button shows a spinner and is disabled to prevent multiple taps.
If login fails, the error message from Firebase is shown in red below the button. If login succeeds, the error message clears and you can add navigation or other logic.
This approach keeps the UI responsive and gives clear feedback to the user.