### Setup UIKit Data Binding Sample Project Source: https://github.com/firebase/firebaseui-ios/blob/main/README.md Navigate to a UIKit data binding sample directory (Database, Firestore, or Storage) and run `pod install`. ```bash $ cd FirebaseDatabaseUI # or FirebaseFirestoreUI, FirebaseStorageUI $ pod install ``` -------------------------------- ### Install FirebaseUI with CocoaPods Source: https://github.com/firebase/firebaseui-ios/blob/main/samples/objc/README.md Clone the repository, navigate to the sample directory, install dependencies using CocoaPods, and open the workspace. ```bash git clone https://github.com/firebase/FirebaseUI-iOS.git cd FirebaseUI-iOS/samples/objc pod install open FirebaseUI-demo-objc.xcworkspace ``` -------------------------------- ### Setup SwiftUI Sample Project Source: https://github.com/firebase/firebaseui-ios/blob/main/README.md Navigate to the SwiftUI sample directory and open the Xcode project for SwiftUI components. ```bash $ cd samples/swiftui/FirebaseSwiftUISample $ open FirebaseSwiftUISample.xcodeproj ``` -------------------------------- ### Full-Featured Authentication Example in SwiftUI Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseSwiftUI/README.md Configure and use AuthService with multiple sign-in providers, email link, MFA, and TOS/privacy policy URLs. This example sets up the authentication service and presents the AuthPickerView to manage the authentication state. ```swift import FirebaseAppleSwiftUI import FirebaseAuthSwiftUI import FirebaseFacebookSwiftUI import FirebaseGoogleSwiftUI import FirebaseOAuthSwiftUI import FirebasePhoneAuthSwiftUI import FirebaseTwitterSwiftUI import SwiftUI struct ContentView: View { let authService: AuthService init() { // Configure email link sign-in let actionCodeSettings = ActionCodeSettings() actionCodeSettings.handleCodeInApp = true actionCodeSettings.url = URL(string: "https://yourapp.firebaseapp.com") actionCodeSettings.setIOSBundleID(Bundle.main.bundleIdentifier!) // Create configuration with options let configuration = AuthConfiguration( shouldAutoUpgradeAnonymousUsers: true, tosUrl: URL(string: "https://example.com/tos"), privacyPolicyUrl: URL(string: "https://example.com/privacy"), emailLinkSignInActionCodeSettings: actionCodeSettings, mfaEnabled: true ) // Initialize AuthService with multiple providers authService = AuthService(configuration: configuration) .withEmailSignIn() .withAppleSignIn() .withGoogleSignIn() .withFacebookSignIn() .withPhoneSignIn() .withTwitterSignIn() .withOAuthSignIn(OAuthProviderSwift.github()) .withOAuthSignIn(OAuthProviderSwift.microsoft()) .withOAuthSignIn(OAuthProviderSwift.yahoo()) } var body: some View { AuthPickerView { // This view handles the presentation of the authentication UI authenticatedContent } .environment(authService) // Inject the authService into the environment } var authenticatedContent: some View { NavigationStack { VStack(spacing: 20) { if authService.authenticationState == .authenticated { Text("Authenticated") Button("Manage Account") { authService.isPresented = true } .buttonStyle(.bordered) Button("Sign Out") { Task { try? await authService.signOut() } } .buttonStyle(.borderedProminent) } else { Text("Not Authenticated") Button("Sign In") { authService.isPresented = true } .buttonStyle(.borderedProminent) } } .navigationTitle("My App") } .onChange(of: authService.authenticationState) { _, newValue in // Automatically show auth UI when not authenticated if newValue != .authenticating { authService.isPresented = (newValue == .unauthenticated) } } } } ``` -------------------------------- ### Clone and Install FirebaseUI Swift Source: https://github.com/firebase/firebaseui-ios/blob/main/samples/swift/README.md Clone the FirebaseUI-iOS repository, navigate to the Swift samples directory, install CocoaPods dependencies, and open the workspace. ```bash git clone https://github.com/firebase/FirebaseUI-iOS.git cd FirebaseUI-iOS/samples/swift pod install open FirebaseUI-demo-swift.xcworkspace ``` -------------------------------- ### Using the Default Table/Collection View Cell Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseDatabaseUI/README.md Demonstrates how to use default UITableViewCell or UICollectionViewCell implementations for quick setup. ```APIDOC ## Swift (UITableViewCell) ```swift self.dataSource = self.tableView.bind(to: firebaseRef) { tableView, indexPath, snap in let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) // Populate cell as you see fit, like as below cell.textLabel?.text = snap.key return cell } ``` ## Swift (UICollectionViewCell) ```swift self.dataSource = self.collectionView.bind(to: firebaseRef) { collectionView, indexPath, snap in let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "reuseIdentifier", for: indexPath) // Populate cell as you see fit cell.contentView.accessibilityLabel = "A cell" return cell } ``` ``` -------------------------------- ### Start MFA Enrollment Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseSwiftUI/README.md Initiates the enrollment process for a second factor (SMS or TOTP). Requires MFA to be enabled in the AuthConfiguration. ```APIDOC ## Start MFA Enrollment ### Description Initiates enrollment for a second factor. ### Method `startMfaEnrollment` ### Parameters - `type` (SecondFactorType) - Required - Type of second factor (`.sms` or `.totp`) - `accountName` (String?) - Optional - Account name for TOTP (defaults to user's email) - `issuer` (String?) - Optional - Issuer name for TOTP (defaults to `configuration.mfaIssuer`) ### Returns `EnrollmentSession` - Containing enrollment information ### Throws `AuthServiceError` - If MFA is not enabled or factor type not allowed ### Requirements `mfaEnabled` must be `true` in `AuthConfiguration` ``` -------------------------------- ### Custom Google Provider Button Example Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseSwiftUI/README.md Implement a fully custom button for Google Sign-In by conforming to AuthProviderUI. This allows complete control over the button's appearance and behavior. ```swift import FirebaseAuthSwiftUI import FirebaseGoogleSwiftUI import FirebaseAppleSwiftUI import SwiftUI // Custom Google Provider UI class CustomGoogleProviderAuthUI: AuthProviderUI { private let typedProvider: GoogleProviderSwift var provider: AuthProviderSwift { typedProvider } let id: String = "google.com" init() { typedProvider = GoogleProviderSwift() } @MainActor func authButton() -> AnyView { AnyView(CustomGoogleButton(provider: typedProvider)) } } struct CustomGoogleButton: View { let provider: GoogleProviderSwift @Environment(AuthService.self) private var authService var body: some View { Button { Task { try? await authService.signIn(provider) } } label: { HStack { Image(systemName: "g.circle.fill") Text("My Custom Google Button") } .frame(maxWidth: .infinity) .padding() .background(Color.purple) // Your custom color .foregroundColor(.white) .cornerRadius(10) } } } // Then use it struct ContentView: View { let authService: AuthService init() { let configuration = AuthConfiguration() authService = AuthService(configuration: configuration) .withAppleSignIn() // Use default Apple button // Use custom Google button authService.registerProvider( providerWithButton: CustomGoogleProviderAuthUI() ) } var body: some View { AuthPickerView { Text("App Content") } .environment(authService) } } ``` -------------------------------- ### Minimal FirebaseUI AuthPickerView Example Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseSwiftUI/README.md Integrate AuthPickerView for a minimal email authentication flow. Ensure the AuthService is configured and provided to the environment. ```swift import FirebaseAuthSwiftUI import SwiftUI struct ContentView: View { let authService: AuthService init() { let configuration = AuthConfiguration() authService = AuthService(configuration: configuration) .withEmailSignIn() } var body: some View { AuthPickerView { // Your authenticated app content goes here Text("Welcome to your app!") } .environment(authService) } } ``` -------------------------------- ### Start MFA Enrollment Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseSwiftUI/README.md Initiates enrollment for a second factor (SMS or TOTP). Requires `mfaEnabled` to be true in `AuthConfiguration`. Account name and issuer are optional for TOTP. ```swift public func startMfaEnrollment( type: SecondFactorType, accountName: String? = nil, issuer: String? = nil ) async throws -> EnrollmentSession ``` -------------------------------- ### Install FirebaseUI Storage with CocoaPods Source: https://github.com/firebase/firebaseui-ios/blob/main/README.md Use this snippet to include only Storage features when using CocoaPods for UIKit data binding. ```ruby pod 'FirebaseUI/Storage' ``` -------------------------------- ### Install FirebaseUI Database with CocoaPods Source: https://github.com/firebase/firebaseui-ios/blob/main/README.md Use this snippet to include only Database features when using CocoaPods for UIKit data binding. ```ruby pod 'FirebaseUI/Database' ``` -------------------------------- ### Custom SwiftUI Authentication Flow Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseSwiftUI/README.md Implement a custom authentication flow using SwiftUI and FirebaseUI's AuthService. This example demonstrates setting up navigation, handling sign-in with Google and phone, and managing authentication states. ```swift import FirebaseAuth import FirebaseAuthSwiftUI import FirebaseGoogleSwiftUI import SwiftUI enum CustomAuthRoute { case signIn case phoneVerification case mfaResolution } struct ContentView: View { private let authService: AuthService @State private var navigationPath: [CustomAuthRoute] = [] @State private var errorMessage: String? init() { let configuration = AuthConfiguration() self.authService = AuthService(configuration: configuration) .withGoogleSignIn() .withPhoneSignIn() } var body: some View { NavigationStack(path: $navigationPath) { Group { if authService.authenticationState == .authenticated { authenticatedView } else { customSignInView } } .navigationDestination(for: CustomAuthRoute.self) { route in switch route { case .signIn: customSignInView case .phoneVerification: customPhoneVerificationView case .mfaResolution: customMFAView } } } .environment(authService) .alert("Error", isPresented: .constant(errorMessage != nil)) { Button("OK") { errorMessage = nil } } message: { Text(errorMessage ?? "") } } var customSignInView: some View { VStack(spacing: 20) { Text("Custom Sign In") .font(.title) Button("Sign in with Google") { Task { do { let provider = GoogleProviderSwift(clientID: Auth.auth().app?.options.clientID ?? "") let outcome = try await authService.signIn(provider) // Handle MFA if required if case .mfaRequired = outcome { navigationPath.append(.mfaResolution) } } catch { errorMessage = error.localizedDescription } } } .buttonStyle(.borderedProminent) Button("Phone Sign In") { navigationPath.append(.phoneVerification) } .buttonStyle(.bordered) } .padding() } var customPhoneVerificationView: some View { Text("Custom Phone Verification View") // Implement your custom phone auth UI here } var customMFAView: some View { Text("Custom MFA Resolution View") // Implement your custom MFA UI here } var authenticatedView: some View { VStack(spacing: 20) { Text("Welcome!") Text("Email: \(authService.currentUser?.email ?? "N/A")") Button("Sign Out") { Task { try? await authService.signOut() } } .buttonStyle(.borderedProminent) } } } ``` -------------------------------- ### Install FirebaseUI Firestore with CocoaPods Source: https://github.com/firebase/firebaseui-ios/blob/main/README.md Use this snippet to include only Firestore features when using CocoaPods for UIKit data binding. ```ruby pod 'FirebaseUI/Firestore' ``` -------------------------------- ### Create Custom Twitter Button UI with Firebase Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseSwiftUI/README.md Implement a custom button for Twitter sign-in using `AuthProviderUI`. This example shows how to create a custom button view, wrap it in an `AuthProviderUI` class, and register it with `AuthService` for use in your application. ```swift import FirebaseAuthSwiftUI import FirebaseTwitterSwiftUI import SwiftUI // Step 1: Create your custom button view struct CustomTwitterButton: View { let provider: TwitterProviderSwift @Environment(AuthService.self) private var authService @Environment(\.mfaHandler) private var mfaHandler var body: some View { Button { Task { do { let outcome = try await authService.signIn(provider) // Handle MFA if required if case let .mfaRequired(mfaInfo) = outcome, let onMFA = mfaHandler { onMFA(mfaInfo) } } catch { // Do Something Else } } } label: { HStack { // Your custom icon Text("Sign in with Twitter") .fontWeight(.semibold) } .frame(maxWidth: .infinity) .padding() .background( LinearGradient( colors: [Color.blue, Color.cyan], startPoint: .leading, endPoint: .trailing ) ) .foregroundColor(.white) .cornerRadius(12) .shadow(radius: 4) } } } // Step 2: Create a custom AuthProviderUI wrapper class CustomTwitterProviderAuthUI: AuthProviderUI { private let typedProvider: TwitterProviderSwift var provider: AuthProviderSwift { typedProvider } let id: String = "twitter.com" init(provider: TwitterProviderSwift = TwitterProviderSwift()) { typedProvider = provider } @MainActor func authButton() -> AnyView { AnyView(CustomTwitterButton(provider: typedProvider)) } } // Step 3: Use it in your app struct ContentView: View { let authService: AuthService init() { let configuration = AuthConfiguration() authService = AuthService(configuration: configuration) // Register your custom provider UI authService.registerProvider( providerWithButton: CustomTwitterProviderAuthUI() ) authService.isPresented = true } var body: some View { AuthPickerView { usersApp } .environment(authService) } var usersApp: some View { NavigationStack { VStack { Button { authService.isPresented = true } label: { Text("Authenticate") } } } } } ``` -------------------------------- ### Configure Firebase App Entry Point Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseSwiftUI/README.md Set up your app's entry point to configure Firebase. This involves creating an AppDelegate to handle application launch and ensuring FirebaseApp.configure() is called. ```swift import FirebaseAuthSwiftUI import FirebaseCore import SwiftUI class AppDelegate: NSObject, UIApplicationDelegate { func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { FirebaseApp.configure() return true } } @main struct YourApp: App { @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate var body: some Scene { WindowGroup { ContentView() } } } ``` -------------------------------- ### Create User with Email and Password Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseSwiftUI/README.md Creates a new user account using the provided email address and password. This method throws errors if user creation fails. ```swift try await authService.createUser(email: "newuser@example.com", password: "securepassword") ``` -------------------------------- ### AuthService Initialization Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseSwiftUI/README.md Initializes the AuthService with optional custom configuration and a Firebase Auth instance. ```swift public init( configuration: AuthConfiguration = AuthConfiguration(), auth: Auth = Auth.auth() ) ``` -------------------------------- ### Sign In with Email and Password Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseSwiftUI/README.md Signs in a user using their email address and password. This method throws errors if authentication fails. ```swift try await authService.signIn(email: "user@example.com", password: "password123") ``` -------------------------------- ### Bind UICollectionView to Firebase Reference (Swift) Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseDatabaseUI/README.md Use FUICollectionViewDataSource to automatically bind a Firebase reference to a UICollectionView. This example shows how to dequeue and populate cells. ```swift self.dataSource = self.collectionView.bind(to: self.firebaseRef) { collectionView, indexPath, snap in let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "reuseIdentifier", for: indexPath) /* populate cell */ return cell } ``` -------------------------------- ### Sign in with Google Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseSwiftUI/README.md Enables Sign in with Google authentication and registers a Google button. An optional provider can be supplied. ```APIDOC ## withGoogleSignIn ### Description Enables Sign in with Google authentication and will register a Google button that is rendered in AuthPickerView (default Views) or can be rendered in custom Views by calling `AuthService.renderButtons()`. ### Method Signature ```swift // Available when importing FirebaseGoogleSwiftUI public func withGoogleSignIn(_ provider: GoogleProviderSwift? = nil) -> AuthService ``` ### Parameters #### Path Parameters - **provider** (`GoogleProviderSwift?`) - Optional - An optional instance of `GoogleProviderSwift`. If not provided, a default instance will be created using the client ID from Firebase configuration. ### Example ```swift authService .withGoogleSignIn() ``` ``` -------------------------------- ### Bind UITableView to Firebase Query (Swift) Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseDatabaseUI/README.md Use FUITableViewDataSource to automatically bind a Firebase query to a UITableView. This example shows how to dequeue and populate cells. ```swift self.dataSource = self.tableView.bind(to: query) { tableView, indexPath, snapshot in // Dequeue cell let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) /* populate cell */ return cell } ``` -------------------------------- ### Placeholder for Reproducing Problem Code Source: https://github.com/firebase/firebaseui-ios/blob/main/ISSUE_TEMPLATE.md Use this section to provide code that helps reproduce the issue you are experiencing. Ensure it is concise and directly related to the problem. ```swift // TODO(you): code here to reproduce the problem ``` -------------------------------- ### Bind UICollectionView to Firebase Reference (Objective-C) Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseDatabaseUI/README.md Use FUICollectionViewDataSource to automatically bind a Firebase reference to a UICollectionView in Objective-C. This example shows how to dequeue and populate cells. ```objectivec self.firebaseRef = [[FIRDatabase database] reference]; self.dataSource = [self.collectionView bindToQuery:self.firebaseRef populateCell:^UICollectionViewCell *(UICollectionView *collectionView, NSIndexPath *indexPath, FIRDataSnapshot *object) { UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuseIdentfier" forIndexPath:indexPath]; /* populate cell */ return cell; }]; ``` -------------------------------- ### Create User with Email/Password Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseSwiftUI/README.md Creates a new user account using the provided email address and password. ```APIDOC ## createUser ### Description Creates a new user account with email and password. ### Method Signature ```swift public func createUser(email email: String, password: String) async throws -> SignInOutcome ``` ### Parameters - `email` (String): New user's email address. - `password` (String): New user's password. ### Returns `SignInOutcome`. ### Throws `AuthServiceError` or Firebase Auth errors. ``` -------------------------------- ### Bind UITableView to Firebase Query (Objective-C) Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseDatabaseUI/README.md Use FUITableViewDataSource to automatically bind a Firebase query to a UITableView in Objective-C. This example shows how to dequeue and populate cells. ```objectivec self.dataSource = [self.tableView bindToQuery:query populateCell:^UITableViewCell *(UITableView *tableView, NSIndexPath *indexPath, FIRDataSnapshot *snap) { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuseIdentifier" forIndexPath:indexPath]; /* populate cell */ return cell; }]; ``` -------------------------------- ### Sign in with Apple Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseSwiftUI/README.md Enables Sign in with Apple authentication and registers an Apple button. An optional provider can be supplied. ```APIDOC ## withAppleSignIn ### Description Enables Sign in with Apple authentication and will register an apple button that is rendered in `AuthPickerView` (default Views) or can be rendered in custom Views by calling `AuthService.renderButtons()`. ### Method Signature ```swift // Available when importing FirebaseAppleSwiftUI public func withAppleSignIn(_ provider: AppleProviderSwift? = nil) -> AuthService ``` ### Parameters #### Path Parameters - **provider** (`AppleProviderSwift?`) - Optional - An optional instance of `AppleProviderSwift`. If not provided, a default instance will be created. ### Example ```swift authService .withAppleSignIn() ``` ``` -------------------------------- ### Use Default UICollectionViewCell with Firebase Data (Swift) Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseDatabaseUI/README.md Bind a Firebase reference to a UICollectionView using the default UICollectionViewCell. This example sets the accessibility label for the cell's contentView. ```swift self.dataSource = self.collectionView.bind(to: firebaseRef) { collectionView, indexPath, snap in let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "reuseIdentifier", for: indexPath) // Populate cell as you see fit cell.contentView.accessibilityLabel = "A cell" return cell } ``` -------------------------------- ### Use Default UITableViewCell with Firebase Data (Swift) Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseDatabaseUI/README.md Bind a Firebase reference to a UITableView using the default UITableViewCell. This example populates the cell's textLabel with the snapshot key. ```swift self.dataSource = self.tableView.bind(to: firebaseRef) { tableView, indexPath, snap in let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) // Populate cell as you see fit, like as below cell.textLabel?.text = snap.key return cell } ``` -------------------------------- ### Configure Generic OAuth Providers Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseSwiftUI/README.md Enables authentication with generic OAuth/OIDC providers. Use this to add built-in providers like GitHub, Microsoft, Yahoo, or custom ones. ```swift authService .withOAuthSignIn(OAuthProviderSwift.github()) .withOAuthSignIn(OAuthProviderSwift.microsoft()) .withOAuthSignIn( OAuthProviderSwift( providerId: "oidc.custom-provider", displayName: "Sign in with Custom", buttonIcon: Image("custom-logo"), buttonBackgroundColor: .blue, buttonForegroundColor: .white ) ) ``` -------------------------------- ### Progressive Image Loading (Objective-C) Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseStorageUI/README.md Enable progressive downloading and decoding for images loaded from Cloud Storage using FIRStorageReference. This can improve perceived performance by displaying a low-resolution version of the image while the full image downloads. ```objective-c // Use progressive downloading and decoding for images [imageView sd_setImageWithStorageReference:reference placeholderImage:placeholderImage options:SDWebImageProgressiveLoad]; ``` -------------------------------- ### Override UI Strings with Localizable.strings Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseSwiftUI/README.md To customize UI text, create a Localizable.strings file and provide your own translations. Use the customStringsBundle parameter in AuthConfiguration to load these strings. ```swift // Localizable.strings "Sign in with Firebase" = "Welcome Back!"; // In your app configuration let configuration = AuthConfiguration(customStringsBundle: .main) ``` -------------------------------- ### Load Image from gs:// URL (Objective-C) Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseStorageUI/README.md Load an image directly from a gs:// URL using StorageImageLoader with SDWebImage. This is useful when you have the storage URL readily available. A placeholder image can be provided. ```objective-c // Use gs:// URL directly with StorageImageLoader NSURL *storageUrl = [NSURL URLWithString:@"gs://..."]; [imageView sd_setImageWithURL:storageUrl placeholderImage:placeholderImage options:0 context:@{SDWebImageContextImageLoader : FUIStorageImageLoader.sharedLoader}]; ``` -------------------------------- ### Sign In with Phone Number Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseSwiftUI/README.md Signs in using a phone number and verification code. ```APIDOC ## signInWithPhoneNumber ### Description Signs in using a phone number and verification code. ### Method Signature ```swift public func signInWithPhoneNumber( verificationID: String, verificationCode: String ) async throws ``` ### Parameters - `verificationID` (String) - The verification ID returned from `verifyPhoneNumber()` - `verificationCode` (String) - The SMS code received by the user ### Throws - `AuthServiceError` or Firebase Auth errors ``` -------------------------------- ### Run SwiftUI Auth Checks Locally Source: https://github.com/firebase/firebaseui-ios/blob/main/CONTRIBUTING.md Execute the SwiftUI Auth GitHub Actions workflow locally. This script runs package unit tests, integration tests, and UI tests by default. Use flags like --unit, --integration, or --ui to run specific checks. Include --lint to run lint-swift.sh beforehand. ```bash ./swiftui-tests.sh ``` ```bash ./swiftui-tests.sh --unit ``` ```bash ./swiftui-tests.sh --integration --ui ``` ```bash ./swiftui-tests.sh --lint --all ``` ```bash ./swiftui-tests.sh --device "iPhone 17 Pro" --ui ``` ```bash FIREBASE_PROJECT="my-firebase-project" ./swiftui-tests.sh --integration ``` -------------------------------- ### Sign In with Email/Password Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseSwiftUI/README.md Authenticates a user using their email address and password. ```APIDOC ## signIn (email:password:) ### Description Signs in using email and password credentials. ### Method Signature ```swift public func signIn(email: String, password: String) async throws -> SignInOutcome ``` ### Parameters - `email` (String): User's email address. - `password` (String): User's password. ### Returns `SignInOutcome`. ### Throws `AuthServiceError` or Firebase Auth errors. ``` -------------------------------- ### Handle Sign-In Link Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseSwiftUI/README.md Handles the email link flow when the user taps the link. Automatically routes to either sign-in or reauthentication based on the current context. ```APIDOC ## handleSignInLink ### Description Handles the email link flow when the user taps the link. Automatically routes to either sign-in or reauthentication based on the current context. ### Method Signature ```swift public func handleSignInLink(url url: URL) async throws ``` ### Parameters - `url` (URL) - The deep link URL from the email ### Throws - `AuthServiceError` or Firebase Auth errors ### Notes This method handles both initial sign-in and reauthentication flows automatically. The behavior is determined by whether `sendEmailSignInLink(email:isReauth:)` was called with `isReauth: true`. ``` -------------------------------- ### AuthPickerView Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseSwiftUI/README.md A pre-built SwiftUI view that provides a complete authentication UI, including MFA flows. ```APIDOC ### AuthPickerView A pre-built view that provides complete authentication UI. ```swift public struct AuthPickerView: View { public init(@ViewBuilder content: @escaping () -> Content = { EmptyView() }) } ``` **Parameters:** - `content`: Your app's authenticated content, shown when user is signed in. **Usage:** ```swift AuthPickerView { // Your app content here Text("Welcome!") } .environment(authService) ``` **Behavior:** - Presents authentication UI as a modal sheet controlled by `authService.isPresented` - Automatically handles navigation between auth screens - Includes built-in error handling and account conflict resolution - Supports MFA flows automatically ``` -------------------------------- ### Load Image from gs:// URL (Swift) Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseStorageUI/README.md Load an image directly from a gs:// URL using StorageImageLoader with SDWebImage in Swift. This is useful when the storage URL is readily available. A placeholder image can be provided. ```swift // Use gs:// URL directly with StorageImageLoader let storageUrl = URL(string: "gs://...") imageView.sd_setImage(with: storageUrl, placeholderImage: placeholderImage, options:[], context: [.imageLoader : StorageImageLoader.shared]) ``` -------------------------------- ### Initialize FUIArray (Swift) Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseDatabaseUI/README.md Initialize an FUIArray to synchronize a Firebase FIRDatabaseReference with an array in Swift. ```swift let firebaseRef = Database.database().reference() let array = FUIArray(query: firebaseRef) ``` -------------------------------- ### Resolve Sign-In with MFA Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseSwiftUI/README.md Completes the sign-in process by verifying the provided MFA code. ```APIDOC ## Resolve Sign-In with MFA ### Description Completes sign-in by verifying the MFA code. ### Method `resolveSignIn` ### Parameters - `code` (String) - Required - The MFA code from SMS or TOTP app - `hintIndex` (Int) - Required - Index of the MFA hint being used - `verificationId` (String?) - Optional - Verification ID (required for SMS, ignored for TOTP) ### Throws `AuthServiceError` ``` -------------------------------- ### Progressive Image Loading (Swift) Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseStorageUI/README.md Enable progressive downloading and decoding for images loaded from Cloud Storage using StorageReference in Swift. This can improve perceived performance by displaying a low-resolution version of the image while the full image downloads. ```swift // Use progressive downloading and decoding for images imageView.sd_setImage(with: reference, placeholderImage: placeholderImage, options: [.progressiveLoad]) ``` -------------------------------- ### Handle Email Sign-In Link Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseSwiftUI/README.md Handles the email link flow for both initial sign-in and reauthentication. Routes based on the context of whether `sendEmailSignInLink(email:isReauth:)` was called with `isReauth: true`. ```swift public func handleSignInLink(url url: URL) async throws ``` -------------------------------- ### Initialize FUIArray (Objective-C) Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseDatabaseUI/README.md Initialize an FUIArray to synchronize a Firebase FIRDatabaseReference with an array in Objective-C. ```objective-c FIRDatabaseReference *firebaseRef = [[FIRDatabase database] reference]; FUIArray *array = [[FUIArray alloc] initWithQuery:firebaseRef]; ``` -------------------------------- ### Render Authentication Buttons Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseSwiftUI/README.md Renders all registered authentication provider buttons in a vertical stack. Customize the spacing between buttons using the `spacing` parameter. ```swift VStack { Text("Choose a sign-in method") authService.renderButtons(spacing: 12) } ``` -------------------------------- ### Load Image from FIRStorageReference (Objective-C) Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseStorageUI/README.md Use the UIImageView+FirebaseStorage extensions to load an image from a FIRStorageReference. This method utilizes SDWebImage for efficient image loading and caching. A placeholder image can be provided. ```objective-c // Objective-C // Reference to an image file in Cloud Storage FIRStorageReference *reference = ...; // UIImageView in your ViewController UIImageView *imageView = ...; // Load the image using SDWebImage [imageView sd_setImageWithStorageReference:reference placeholderImage:placeholderImage]; ``` -------------------------------- ### Sign In with Credential Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseSwiftUI/README.md Signs in using a provider that conforms to CredentialAuthProviderSwift. Returns either a successful sign-in outcome or indicates that MFA is required. ```APIDOC ## signIn (CredentialAuthProviderSwift) ### Description Signs in using a provider that conforms to `CredentialAuthProviderSwift`. ### Method Signature ```swift public func signIn(_ provider: CredentialAuthProviderSwift) async throws -> SignInOutcome ``` ### Parameters - `provider` (CredentialAuthProviderSwift): The authentication provider to use. ### Returns `SignInOutcome` - either `.signedIn(AuthDataResult?)` or `.mfaRequired(MFARequired)`. ### Throws `AuthServiceError` or Firebase Auth errors. ### Example ```swift Task { do { let outcome = try await authService.signIn(GoogleProviderSwift()) switch outcome { case .signedIn(let result): print("Signed in: \(result?.user.email ?? "")") case .mfaRequired(let mfaInfo): // Handle MFA resolution print("MFA required: \(mfaInfo)") } } catch { print("Sign in error: \(error)") } } ``` ``` -------------------------------- ### Render Authentication Buttons Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseSwiftUI/README.md Renders all registered authentication provider buttons as a vertical stack. ```APIDOC ## renderButtons ### Description Renders all registered authentication provider buttons as a vertical stack. ### Method Signature ```swift public func renderButtons(spacing: CGFloat = 16) -> AnyView ``` ### Parameters - `spacing` (CGFloat): Vertical spacing between buttons (default: 16). ### Returns An `AnyView` containing all auth buttons. ### Example ```swift VStack { Text("Choose a sign-in method") authService.renderButtons(spacing: 12) } ``` ``` -------------------------------- ### Resolve Sign-In with MFA Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseSwiftUI/README.md Completes the sign-in process by verifying the MFA code. Requires the code, hint index, and optionally a verification ID for SMS. ```swift public func resolveSignIn( code: String, hintIndex: Int, verificationId: String? = nil ) async throws ``` -------------------------------- ### AuthConfiguration Struct Definition Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseSwiftUI/README.md Defines the configurable options for the authentication flow, including UI elements, language codes, and MFA settings. ```swift public struct AuthConfiguration { public init( logo: ImageResource? = nil, languageCode: String? = nil, shouldHideCancelButton: Bool = false, interactiveDismissEnabled: Bool = true, shouldAutoUpgradeAnonymousUsers: Bool = false, customStringsBundle: Bundle? = nil, tosUrl: URL? = nil, privacyPolicyUrl: URL? = nil, emailLinkSignInActionCodeSettings: ActionCodeSettings? = nil, verifyEmailActionCodeSettings: ActionCodeSettings? = nil, mfaEnabled: Bool = false, allowedSecondFactors: Set = [.sms, .totp], mfaIssuer: String = "Firebase Auth" ) } ``` -------------------------------- ### Load Image from StorageReference (Swift) Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseStorageUI/README.md Use the UIImageView+FirebaseStorage extensions in Swift to load an image from a StorageReference. This method leverages SDWebImage for efficient image loading and caching. A placeholder image can be provided. ```swift // Swift // Reference to an image file in Cloud Storage let reference: StorageReference = ... // UIImageView in your ViewController let imageView: UIImageView = ... // Load the image using SDWebImage imageView.sd_setImage(with: reference, placeholderImage: placeholderImage) ``` -------------------------------- ### CocoaPods Project Configuration Source: https://github.com/firebase/firebaseui-ios/blob/main/README.md Ensure these settings are present in your Podfile when using CocoaPods for FirebaseUI. ```ruby platform :ios, '13.0' use_frameworks! ``` -------------------------------- ### Enable Sign in with Apple using FirebaseUI Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseSwiftUI/README.md Enables Sign in with Apple authentication. An optional `AppleProviderSwift` can be provided for custom configurations. ```swift authService .withAppleSignIn() ``` -------------------------------- ### Enable Sign in with Google using FirebaseUI Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseSwiftUI/README.md Enables Sign in with Google authentication. An optional `GoogleProviderSwift` can be provided for custom configurations. ```swift authService .withGoogleSignIn() ``` -------------------------------- ### AuthService Public Properties Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseSwiftUI/README.md Provides access to essential configuration and state information for the authentication service, including configuration, Firebase Auth instance, presentation state, current user, authentication state, flow, navigator, and the currently displayed auth view. ```swift public let configuration: AuthConfiguration ``` ```swift public let auth: Auth ``` ```swift public var isPresented: Bool ``` ```swift public var currentUser: User? ``` ```swift public var authenticationState: AuthenticationState ``` ```swift public var authenticationFlow: AuthenticationFlow ``` ```swift public private(set) var navigator: Navigator ``` ```swift public var authView: AuthView? ``` -------------------------------- ### AuthPickerView Usage Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseSwiftUI/README.md A pre-built SwiftUI view that provides a complete authentication UI. It automatically handles navigation, error handling, MFA flows, and presents authentication UI as a modal sheet. ```swift public struct AuthPickerView: View { public init(@ViewBuilder content: @escaping () -> Content = { EmptyView() }) } ``` ```swift AuthPickerView { // Your app content here Text("Welcome!") } .environment(authService) ``` -------------------------------- ### Sign in with Facebook Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseSwiftUI/README.md Enables Sign in with Facebook authentication and registers a Facebook button. An optional provider can be supplied. ```APIDOC ## withFacebookSignIn ### Description Enables Sign in with Facebook authentication and will register a Facebook button that is rendered in AuthPickerView (default Views) or can be rendered in custom Views by calling `AuthService.renderButtons()`. ### Method Signature ```swift // Available when importing FirebaseFacebookSwiftUI public func withFacebookSignIn(_ provider: FacebookProviderSwift? = nil) -> AuthService ``` ### Parameters #### Path Parameters - **provider** (`FacebookProviderSwift?`) - Optional - An optional instance of `FacebookProviderSwift()` for classic login or `FacebookProviderSwift(useClassicLogin: false)` for limited login. If not provided, a default instance with classic login will be created. ### Example ```swift authService .withFacebookSignIn() ``` ``` -------------------------------- ### Observe Firestore Query with FUIBatchedArray Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseFirestoreUI/README.md Initialize and observe a Firestore query directly using FUIBatchedArray. This is useful for custom UI implementations that require direct data management and diffing. ```swift let array = FUIBatchedArray(query: query, delegate: self) array.observeQuery() ``` -------------------------------- ### AuthConfiguration Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseSwiftUI/README.md The AuthConfiguration struct allows you to customize the behavior and appearance of the authentication flow, including UI strings, logos, and URLs. ```APIDOC ## AuthConfiguration ### Description Customizes the behavior and appearance of the authentication flow. ### Initializer ```swift public init( logo: ImageResource? = nil, languageCode: String? = nil, shouldHideCancelButton: Bool = false, interactiveDismissEnabled: Bool = true, shouldAutoUpgradeAnonymousUsers: Bool = false, customStringsBundle: Bundle? = nil, tosUrl: URL? = nil, privacyPolicyUrl: URL? = nil, emailLinkSignInActionCodeSettings: ActionCodeSettings? = nil, verifyEmailActionCodeSettings: ActionCodeSettings? = nil, mfaEnabled: Bool = false, allowedSecondFactors: Set = [.sms, .totp], mfaIssuer: String = "Firebase Auth" ) ``` ### Parameters #### Initializer Parameters - **logo** (`ImageResource?`) - Optional: Custom logo to display in the authentication UI. Defaults to the Firebase logo. - **languageCode** (`String?`) - Optional: Language code for localized strings (e.g., "en", "es", "fr"). Defaults to the system language. - **shouldHideCancelButton** (`Bool`) - Optional: If `true`, hides the cancel button in auth flows. Defaults to `false`. - **interactiveDismissEnabled** (`Bool`) - Optional: If `false`, prevents users from dismissing auth sheets by swiping down. Defaults to `true`. - **shouldAutoUpgradeAnonymousUsers** (`Bool`) - Optional: If `true`, automatically links anonymous user accounts with new sign-in credentials. Defaults to `false`. - **customStringsBundle** (`Bundle?`) - Optional: Custom bundle for string localizations. Allows overriding default strings. - **tosUrl** (`URL?`) - Optional: URL to your Terms of Service. Displayed when `privacyPolicyUrl` is also set. - **privacyPolicyUrl** (`URL?`) - Optional: URL to your Privacy Policy. Displayed when `tosUrl` is also set. - **emailLinkSignInActionCodeSettings** (`ActionCodeSettings?`) - Optional: Configuration for email link (passwordless) sign-in. Required for email link authentication. - **verifyEmailActionCodeSettings** (`ActionCodeSettings?`) - Optional: Configuration for email verification. - **mfaEnabled** (`Bool`) - Optional: Enables Multi-Factor Authentication support. Defaults to `false`. - **allowedSecondFactors** (`Set`) - Optional: Set of allowed MFA factor types. Defaults to `[.sms, .totp]`. - **mfaIssuer** (`String`) - Optional: The issuer name displayed in TOTP authenticator apps. Defaults to `"Firebase Auth"`. ### Notes - Both `tosUrl` and `privacyPolicyUrl` must be set for the links to appear in the UI. - `emailLinkSignInActionCodeSettings` requires `handleCodeInApp = true`, a valid `url`, and an iOS bundle ID configured via `setIOSBundleID()`. ``` -------------------------------- ### AuthService Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseSwiftUI/README.md The main service class that manages authentication state and operations. ```APIDOC ## AuthService ### Description Manages authentication state and operations. ### Initialization ```swift public init( configuration: AuthConfiguration = AuthConfiguration(), auth: Auth = Auth.auth() ) ``` #### Parameters - **configuration** (`AuthConfiguration`) - Configuration for auth behavior. Defaults to `AuthConfiguration()`. - **auth** (`Auth`) - Firebase Auth instance to use. Defaults to `Auth.auth()`. ``` -------------------------------- ### Email Authentication Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseSwiftUI/README.md Enables email authentication and renders email sign-in within the AuthPickerView. A custom callback can be provided for tap events. ```APIDOC ## withEmailSignIn ### Description Enables email authentication and will render email sign-in directly within the AuthPickerView (default Views), email link sign-in is rendered as a button. When calling `AuthService.renderButtons()`, email link sign-in button is rendered. `onTap` custom callback (i.e where to navigate when tapped) allows user to control what happens when tapped. Default behavior in AuthPickerView is to push the user to email link sign-in default View. ### Method Signature ```swift public func withEmailSignIn(onTap: @escaping () -> Void = {}) -> AuthService ``` ### Parameters #### Closure Parameter - **onTap** (`@escaping () -> Void`) - Required/Optional - A callback that will be executed when the email button is tapped. ### Example ```swift authService .withEmailSignIn() // or authService .withEmailSignIn() { // navigate to email sign-in screen logic } ``` ``` -------------------------------- ### Enable Email Sign-In with FirebaseUI Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseSwiftUI/README.md Enables email authentication. Use the `onTap` callback to customize navigation when the email button is tapped. ```swift authService .withEmailSignIn() ``` ```swift authService .withEmailSignIn() { // navigate to email sign-in screen logic } ``` -------------------------------- ### Generic OAuth Providers Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseSwiftUI/README.md Enables authentication with generic OAuth/OIDC providers. This method registers an OAuth button that can be rendered in AuthPickerView or custom Views by calling AuthService.renderButtons(). ```APIDOC ## withOAuthSignIn ### Description Enables authentication with generic OAuth/OIDC providers and will register an OAuth button that is rendered in AuthPickerView (default Views) or can be rendered in custom Views by calling `AuthService.renderButtons()`. ### Method Signature ```swift public func withOAuthSignIn(_ provider: OAuthProviderSwift) -> AuthService ``` ### Parameters - `provider` (OAuthProviderSwift): An instance of OAuthProviderSwift representing the OAuth provider (e.g., GitHub, Microsoft, Yahoo, or a custom provider). ### Built-in Providers - `OAuthProviderSwift.github()` - `OAuthProviderSwift.microsoft()` - `OAuthProviderSwift.yahoo()` ### Custom Provider ```swift OAuthProviderSwift( providerId: String, displayName: String, buttonIcon: Image, buttonBackgroundColor: Color, buttonForegroundColor: Color ) ``` ### Example ```swift authService .withOAuthSignIn(OAuthProviderSwift.github()) .withOAuthSignIn(OAuthProviderSwift.microsoft()) .withOAuthSignIn( OAuthProviderSwift( providerId: "oidc.custom-provider", displayName: "Sign in with Custom", buttonIcon: Image("custom-logo"), buttonBackgroundColor: .blue, buttonForegroundColor: .white ) ) ``` ``` -------------------------------- ### SignInOutcome Enum Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseSwiftUI/README.md Defines the possible outcomes of a sign-in attempt, either a successful sign-in with optional user data or a requirement for Multi-Factor Authentication. ```swift public enum SignInOutcome { case mfaRequired(MFARequired) case signedIn(AuthDataResult?) } ``` -------------------------------- ### Link User Accounts Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseSwiftUI/README.md Links a new authentication method to the current user's account. Requires a valid AuthCredential object. ```swift try await authService.linkAccounts(credentials: someAuthCredential) ``` -------------------------------- ### Link Accounts Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseSwiftUI/README.md Links a new authentication method to the current user's account. ```APIDOC ## linkAccounts ### Description Links a new authentication method to the current user's account. ### Method Signature ```swift public func linkAccounts(credentials credentials: AuthCredential) async throws ``` ### Parameters - `credentials` (AuthCredential): The credential to link. ### Throws `AuthServiceError` or Firebase Auth errors. ``` -------------------------------- ### Reauthenticate Email/Password for Password Update Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseSwiftUI/README.md Catch the .emailReauthenticationRequired error, prompt for the user's password, create a credential, and reauthenticate before retrying the password update. ```swift do { try await authService.updatePassword(to: newPassword) } catch let error as AuthServiceError { if case .emailReauthenticationRequired(let context) = error { // Show your password prompt UI let password = await promptUserForPassword() let credential = EmailAuthProvider.credential( withEmail: context.email, password: password ) try await authService.reauthenticate(with: credential) try await authService.updatePassword(to: newPassword) // Retry } } ``` -------------------------------- ### Sign in with Twitter Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseSwiftUI/README.md Enables Sign in with Twitter authentication and registers a Twitter button. An optional provider can be supplied. ```APIDOC ## withTwitterSignIn ### Description Enables Sign in with Twitter authentication and will register a Twitter button that is rendered in AuthPickerView (default Views) or can be rendered in custom Views by calling `AuthService.renderButtons()`. ### Method Signature ```swift // Available when importing FirebaseTwitterSwiftUI public func withTwitterSignIn(_ provider: TwitterProviderSwift? = nil) -> AuthService ``` ### Parameters #### Path Parameters - **provider** (`TwitterProviderSwift?`) - Optional - An optional instance of `TwitterProviderSwift`. If not provided, a default instance will be created. ### Example ```swift authService .withTwitterSignIn() ``` ``` -------------------------------- ### Enable Sign in with Facebook using FirebaseUI Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseSwiftUI/README.md Enables Sign in with Facebook authentication. An optional `FacebookProviderSwift` can be provided for classic or limited login. ```swift authService .withFacebookSignIn() ``` -------------------------------- ### Send Email Sign-In Link Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseSwiftUI/README.md Sends a passwordless sign-in link to the specified email address. This can also be used for reauthentication. ```APIDOC ## sendEmailSignInLink ### Description Sends a sign-in link to the specified email address. Can also be used for reauthentication. ### Method Signature ```swift public func sendEmailSignInLink(email: String, isReauth: Bool = false) async throws ``` ### Parameters - `email` (String): Email address to send the link to. - `isReauth` (Bool): Whether this is for reauthentication (default: `false`). ### Throws `AuthServiceError` or Firebase Auth errors. ### Requirements `emailLinkSignInActionCodeSettings` must be configured in `AuthConfiguration`. ### Note When `isReauth` is `true`, the method stores the email for reauthentication flow. The same `handleSignInLink(url:)` method handles both sign-in and reauthentication automatically. ``` -------------------------------- ### Verify Phone Number for Authentication Source: https://github.com/firebase/firebaseui-ios/blob/main/FirebaseSwiftUI/README.md Sends a verification code to a specified phone number. Requires the phone number in E.164 format. ```swift public func verifyPhoneNumber(phoneNumber: String) async throws -> String ```