Bird
Raised Fist0
iOS Swiftmobile~20 mins

Firebase Authentication in iOS Swift - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Login Screen
This screen allows users to sign in using their email and password with Firebase Authentication. It shows input fields for email and password, a login button, and displays error messages if login fails.
Target UI
-------------------------
|       Login Screen     |
|-----------------------|
| Email: [___________]  |
| Password: [________]  |
|                       |
|       [Login]         |
|                       |
|  Error message here    |
-------------------------
Two TextFields: one for email, one for password
A Login button that triggers Firebase Authentication sign-in
Show an error message below the button if login fails
Disable the Login button while authentication is in progress
Use secure text entry for password field
Starter Code
iOS Swift
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: {
                // TODO: Add login action
            }) {
                Text("Login")
                    .frame(maxWidth: .infinity)
                    .padding()
                    .background(Color.blue)
                    .foregroundColor(.white)
                    .cornerRadius(8)
            }
            .disabled(isLoading)

            if !errorMessage.isEmpty {
                Text(errorMessage)
                    .foregroundColor(.red)
                    .multilineTextAlignment(.center)
            }

            Spacer()
        }
        .padding()
    }
}

struct LoginScreen_Previews: PreviewProvider {
    static var previews: some View {
        LoginScreen()
    }
}
Task 1
Task 2
Task 3
Task 4
Task 5
Solution
iOS Swift
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.

Final Result
Completed Screen
-------------------------
|       Login Screen     |
|-----------------------|
| Email: [user@example] |
| Password: [********]  |
|                       |
|       [Login]         |
|                       |
|  Invalid password      |
-------------------------
User types email and password in the fields
User taps Login button
Button shows a spinner while authenticating
If login fails, error message appears below button
If login succeeds, error message disappears and app can navigate
Stretch Goal
Add a 'Show Password' toggle button to reveal or hide the password text
💡 Hint
Use a @State Boolean to toggle SecureField and TextField for password input

Practice

(1/5)
1. What is the main purpose of Firebase Authentication in an iOS app?
easy
A. To send push notifications to users
B. To store large files in the cloud
C. To design the app's user interface
D. To let users sign up and log in easily

Solution

  1. Step 1: Understand Firebase Authentication's role

    Firebase Authentication helps manage user sign-up and sign-in processes.
  2. Step 2: Compare options with this role

    Only To let users sign up and log in easily matches this purpose; others relate to different Firebase features or app functions.
  3. Final Answer:

    To let users sign up and log in easily -> Option D
  4. Quick Check:

    Firebase Authentication = User sign-in [OK]
Hint: Firebase Auth is for user login/signup only [OK]
Common Mistakes:
  • Confusing Authentication with storage or UI design
  • Thinking it handles notifications
  • Assuming it manages app layout
2. Which Swift code snippet correctly creates a new user with Firebase Authentication?
easy
A. Auth.signIn(withEmail: email, password: password)
B. Auth.auth().createUser(withEmail: email, password: password) { result, error in }
C. FirebaseAuth.createUser(email, password)
D. Auth.createUser(email: email, password: password)

Solution

  1. Step 1: Recall correct Firebase method for user creation

    The method is Auth.auth().createUser(withEmail:password:completion:).
  2. Step 2: Check each option's syntax

    Only Auth.auth().createUser(withEmail: email, password: password) { result, error in } uses the correct method and parameters; others are invalid or for sign-in.
  3. Final Answer:

    Auth.auth().createUser(withEmail: email, password: password) { result, error in } -> Option B
  4. Quick Check:

    Create user method = Auth.auth().createUser(withEmail: email, password: password) { result, error in } [OK]
Hint: Use Auth.auth().createUser for new users [OK]
Common Mistakes:
  • Using signIn method instead of createUser
  • Wrong method call without Auth.auth()
  • Missing completion handler closure
3. What will be printed if the following Swift code runs and the user enters a wrong password?
Auth.auth().signIn(withEmail: email, password: wrongPassword) { authResult, error in
  if let error = error {
    print("Login failed: \(error.localizedDescription)")
  } else {
    print("Login successful")
  }
}
medium
A. Login failed: The password is invalid or the user does not have a password.
B. No output
C. Login successful
D. Crash due to missing error handling

Solution

  1. Step 1: Understand signIn completion handler behavior

    If sign-in fails, error is non-nil and prints the error message.
  2. Step 2: Analyze wrong password case

    Wrong password triggers error with message about invalid password.
  3. Final Answer:

    Login failed: The password is invalid or the user does not have a password. -> Option A
  4. Quick Check:

    Error message prints on wrong password [OK]
Hint: Errors print message; success prints success [OK]
Common Mistakes:
  • Assuming success prints even on error
  • Ignoring error optional unwrapping
  • Expecting no output on failure
4. Identify the error in this Swift Firebase sign-in code:
Auth.auth().signIn(withEmail: email, password: password) { authResult, error in
  if error != nil {
    print("Error signing in")
  }
  print("User signed in")
}
medium
A. Missing else block causes "User signed in" to print even on error
B. Incorrect method name for signIn
C. No completion handler provided
D. Password parameter is missing

Solution

  1. Step 1: Review control flow in completion handler

    Code prints "User signed in" regardless of error presence.
  2. Step 2: Identify missing else block

    Without else, success message prints even if sign-in failed.
  3. Final Answer:

    Missing else block causes "User signed in" to print even on error -> Option A
  4. Quick Check:

    Print success only if no error [OK]
Hint: Use else to separate success from error prints [OK]
Common Mistakes:
  • Printing success message unconditionally
  • Not checking error properly
  • Confusing method names
5. You want to create a Swift function that registers a user and shows an alert with success or error message. Which approach correctly handles this using Firebase Authentication?
hard
A. Call createUser, then immediately show success alert without waiting for completion
B. Call signIn instead of createUser for registration
C. Call createUser with completion handler, show alert inside handler based on error or success
D. Use createUser without email or password parameters

Solution

  1. Step 1: Understand asynchronous nature of createUser

    createUser runs asynchronously; alerts must be shown after completion.
  2. Step 2: Choose correct alert timing and method

    Showing alert inside completion handler ensures correct success or error message.
  3. Step 3: Eliminate incorrect options

    Call createUser, then immediately show success alert without waiting for completion shows alert too early; C uses wrong method; D misses required parameters.
  4. Final Answer:

    Call createUser with completion handler, show alert inside handler based on error or success -> Option C
  5. Quick Check:

    Show alert after createUser completes [OK]
Hint: Show alerts only inside completion handlers [OK]
Common Mistakes:
  • Showing alerts before async call finishes
  • Using signIn for registration
  • Omitting required parameters
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard