Bird
Raised Fist0
iOS Swiftmobile~20 mins

Analytics and Crashlytics in iOS Swift - Mini App: Build & Ship

Choose your learning style10 modes available
Build: AnalyticsCrashlyticsDemo
This screen demonstrates basic integration of Firebase Analytics and Crashlytics in an iOS app. It tracks button taps as analytics events and simulates a crash to test Crashlytics reporting.
Target UI
-------------------------
| Analytics & Crashlytics |
|-----------------------|
| [Log Event Button]     |
|                       |
| [Cause Crash Button]   |
-------------------------
Add a button labeled 'Log Event Button' that logs a custom analytics event named 'button_tapped' with a parameter 'button_name' set to 'log_event'.
Add a button labeled 'Cause Crash Button' that triggers a crash to test Crashlytics.
Initialize Firebase in the app.
Ensure buttons are accessible with proper labels.
Use SwiftUI for UI implementation.
Starter Code
iOS Swift
import SwiftUI
import Firebase

@main
struct AnalyticsCrashlyticsDemoApp: App {
  init() {
    FirebaseApp.configure()
  }

  var body: some Scene {
    WindowGroup {
      ContentView()
    }
  }
}

struct ContentView: View {
  var body: some View {
    VStack(spacing: 20) {
      // TODO: Add Log Event Button here
      // TODO: Add Cause Crash Button here
    }
    .padding()
  }
}
Task 1
Task 2
Task 3
Solution
iOS Swift
import SwiftUI
import Firebase

@main
struct AnalyticsCrashlyticsDemoApp: App {
  init() {
    FirebaseApp.configure()
  }

  var body: some Scene {
    WindowGroup {
      ContentView()
    }
  }
}

struct ContentView: View {
  var body: some View {
    VStack(spacing: 20) {
      Button("Log Event Button") {
        Analytics.logEvent("button_tapped", parameters: ["button_name": "log_event"])
      }
      .accessibilityLabel("Log Event Button")
      .buttonStyle(.borderedProminent)

      Button("Cause Crash Button") {
        fatalError("Test Crash triggered")
      }
      .accessibilityLabel("Cause Crash Button")
      .buttonStyle(.bordered)
    }
    .padding()
  }
}

We start by configuring Firebase in the app's initializer to enable Analytics and Crashlytics.

The UI uses SwiftUI with two buttons stacked vertically.

The first button logs a custom event named button_tapped with a parameter button_name set to log_event. This helps track user interaction in Analytics.

The second button triggers a crash using fatalError to test Crashlytics crash reporting.

Both buttons have accessibility labels for screen readers and use SwiftUI's button styles for clear visual distinction.

Final Result
Completed Screen
-------------------------
| Analytics & Crashlytics |
|-----------------------|
| [Log Event Button]     |
|                       |
| [Cause Crash Button]   |
-------------------------
Tapping 'Log Event Button' sends a custom event to Firebase Analytics.
Tapping 'Cause Crash Button' immediately crashes the app to test Crashlytics reporting.
Stretch Goal
Add a Text view that shows the count of how many times the 'Log Event Button' was tapped during the current app session.
💡 Hint
Use a @State variable to track the tap count and update it inside the button's action closure.

Practice

(1/5)
1. What is the main purpose of using Analytics in an iOS app?
easy
A. To track user actions and app usage patterns
B. To report app crashes and errors
C. To improve app performance by optimizing code
D. To manage app permissions and privacy settings

Solution

  1. Step 1: Understand Analytics role

    Analytics collects data about how users interact with the app, like button taps or screen views.
  2. Step 2: Differentiate from Crashlytics

    Crashlytics focuses on crash reports, not user behavior tracking.
  3. Final Answer:

    To track user actions and app usage patterns -> Option A
  4. Quick Check:

    Analytics = user action tracking [OK]
Hint: Analytics tracks usage; Crashlytics tracks crashes [OK]
Common Mistakes:
  • Confusing Analytics with Crashlytics
  • Thinking Analytics fixes crashes
  • Assuming Analytics manages permissions
2. Which Swift code snippet correctly logs a custom event named "purchase_complete" using Firebase Analytics?
easy
A. Analytics.logEvent("purchase_complete", parameters: [:])
B. Analytics.logEvent(purchase_complete, parameters: [:])
C. Analytics.logEvent("purchase_complete", parameters: "nil")
D. Analytics.logEvent('purchase_complete')

Solution

  1. Step 1: Check method signature

    The correct method requires event name as a string and parameters as a dictionary (can be empty).
  2. Step 2: Validate syntax correctness

    Analytics.logEvent("purchase_complete", parameters: [:]) uses a string event name and an empty dictionary, matching the required syntax.
  3. Final Answer:

    Analytics.logEvent("purchase_complete", parameters: [:]) -> Option A
  4. Quick Check:

    Correct syntax = Analytics.logEvent("purchase_complete", parameters: [:]) [OK]
Hint: Event name as string, parameters as dictionary [OK]
Common Mistakes:
  • Missing quotes around event name
  • Passing nil instead of dictionary
  • Omitting parameters argument
3. Given the following Swift code snippet using Crashlytics, what will happen when a crash occurs?
Crashlytics.crashlytics().log("User tapped buy button")
fatalError("Simulated crash")
medium
A. The app crashes but the log message is lost
B. The log message causes a runtime error
C. The app does not crash because log prevents it
D. The log message is sent to Crashlytics before the app crashes

Solution

  1. Step 1: Understand Crashlytics log behavior

    Calling log records a message that is sent to Crashlytics on next app launch after a crash.
  2. Step 2: Analyze crash trigger

    fatalError causes an immediate crash, but the log message is preserved for reporting.
  3. Final Answer:

    The log message is sent to Crashlytics before the app crashes -> Option D
  4. Quick Check:

    Crashlytics logs persist through crash [OK]
Hint: Crashlytics logs survive crashes for later reporting [OK]
Common Mistakes:
  • Assuming logs are lost on crash
  • Thinking log prevents crash
  • Confusing log with error throwing
4. You added Crashlytics to your app but crash reports are not showing up in the Firebase console. Which of these is the most likely cause?
medium
A. You used fatalError instead of assert
B. You forgot to call Crashlytics.crashlytics().setCrashlyticsCollectionEnabled(true)
C. You did not import UIKit in your Swift file
D. You called Analytics.logEvent instead of Crashlytics methods

Solution

  1. Step 1: Check Crashlytics setup requirements

    Crashlytics requires enabling data collection explicitly or via Info.plist to send crash reports.
  2. Step 2: Identify missing configuration

    Not calling setCrashlyticsCollectionEnabled(true) disables crash report sending.
  3. Final Answer:

    You forgot to call Crashlytics.crashlytics().setCrashlyticsCollectionEnabled(true) -> Option B
  4. Quick Check:

    Enable collection to send crash reports [OK]
Hint: Enable Crashlytics collection to receive reports [OK]
Common Mistakes:
  • Confusing Analytics logging with Crashlytics setup
  • Missing import statements
  • Thinking crash method choice affects reporting
5. You want to log a user property "user_level" with value "gold" in Firebase Analytics and also log a non-fatal error in Crashlytics when a payment fails. Which Swift code snippet correctly does both?
hard
A. Analytics.setUserProperty("user_level", forName: "gold") Crashlytics.crashlytics().record(error: Error("Payment failed"))
B. Analytics.logEvent("user_level", parameters: ["gold"]) Crashlytics.crashlytics().log("Payment failed")
C. Analytics.setUserProperty("gold", forName: "user_level") Crashlytics.crashlytics().record(error: NSError(domain: "Payment", code: 1, userInfo: nil))
D. Analytics.setUserProperty("gold", forName: "user_level") Crashlytics.crashlytics().log("Payment failed")

Solution

  1. Step 1: Set user property correctly

    Use setUserProperty(_:forName:) with value first, then property name.
  2. Step 2: Log non-fatal error properly

    Use record(error:) with an NSError instance to report non-fatal errors.
  3. Final Answer:

    Analytics.setUserProperty("gold", forName: "user_level") Crashlytics.crashlytics().record(error: NSError(domain: "Payment", code: 1, userInfo: nil)) -> Option C
  4. Quick Check:

    User property + non-fatal error = Analytics.setUserProperty("gold", forName: "user_level") Crashlytics.crashlytics().record(error: NSError(domain: "Payment", code: 1, userInfo: nil)) [OK]
Hint: User property value first, use record(error:) for non-fatal errors [OK]
Common Mistakes:
  • Swapping user property name and value
  • Using log() instead of record(error:) for errors
  • Passing wrong types to methods
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