### Complete Messaging Setup Example Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/firebase-messaging.md A comprehensive example demonstrating the full setup process for Firebase Messaging, including initialization, permission requests, token registration, and topic subscriptions. ```csharp public async Task CompleteMessagingSetup() { try { // Initialize Firebase MauiFIRApp.AutoConfigure(); // Request notification permissions var permStatus = await Permissions.RequestAsync(); if (permStatus == PermissionStatus.Granted) { // Get APNs token and register with FCM var apnsToken = await GetAPNsTokenFromSystem(); var fcmToken = await MauiFIRMessaging.RegisterAsync(apnsToken); Debug.WriteLine($"FCM registered with token: {fcmToken}"); // Subscribe to default topics await MauiFIRMessaging.SubscribeAsync("all_users"); await MauiFIRMessaging.SubscribeAsync($"user_{userId}"); Debug.WriteLine("Push notifications enabled"); } else { Debug.WriteLine("Notification permission denied"); } } catch (Exception ex) { Debug.WriteLine($"Messaging setup failed: {ex.Message}"); } } ``` -------------------------------- ### Basic Setup: Initialize in OnAppearing Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/googlecast.md Shows how to initialize the GoogleCastManager when the page appears. ```APIDOC ## Basic Setup ### Initialize in OnAppearing ```csharp public partial class MainPage : ContentPage { GoogleCastManager? castManager; public MainPage() { InitializeComponent(); } protected override async void OnAppearing() { base.OnAppearing(); if (castManager is null) { castManager = new GoogleCastManager(); castManager.Configure(); #if IOS await Permissions.RequestAsync(); #endif } } } ``` ``` -------------------------------- ### Firebase Initialization Patterns Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/MANIFEST.md Examples demonstrating various ways to initialize Firebase services within a MAUI application. ```csharp await MauiFIRApp.AutoConfigureAsync(); ``` ```csharp await MauiFIRApp.ConfigureAsync("GoogleService-Info.plist"); ``` -------------------------------- ### Example GoogleService-Info.plist Content Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/configuration.md This is an example of the XML content for the GoogleService-Info.plist file used for Firebase configuration on iOS and macOS. It includes essential keys for connecting to your Firebase project. ```xml CLIENT_ID 123456789-abcdef.apps.googleusercontent.com REVERSED_CLIENT_ID com.googleusercontent.apps.123456789-abcdef API_KEY AIzaSyD1234567890abcdefghijklmnopqrstuv GCM_SENDER_ID 123456789 PROJECT_ID my-firebase-project BUNDLE_ID com.example.app GOOGLE_APP_ID 1:123456789:ios:abcdef1234567890abcdef DATABASE_URL https://my-firebase-project.firebaseio.com STORAGE_BUCKET my-firebase-project.appspot.com ``` -------------------------------- ### Create and Setup GoogleCastButton Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/googlecast.md Demonstrates how to create an instance of GoogleCastButton and add it to your view hierarchy. Ensure you have the necessary using statements for GoogleCast and UIKit. ```csharp using GoogleCast; using UIKit; public class GoogleCastButtonHandler : UIView { GoogleCastButton castButton; public void SetupCastButton() { // Create a Google Cast button castButton = new GoogleCastButton(); // Add to your view hierarchy AddSubview(castButton); // Position and style as needed castButton.Frame = new CGRect(10, 10, 50, 50); } } ``` -------------------------------- ### Google Cast Implementation Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/MANIFEST.md Code examples for configuring and using the Google Cast SDK within a MAUI application. ```csharp GoogleCastManager.Configure(new GoogleCastOptions("MyCastAppId")); ``` ```csharp await GoogleCastManager.LoadMediaAsync(mediaInfo); ``` ```csharp var isCasting = GoogleCastManager.IsCastSessionActive; ``` -------------------------------- ### Create Empty NSDictionary Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/types.md Initializes an empty NSDictionary. This is the starting point for building dictionaries programmatically. ```csharp var emptyDict = new NSDictionary(); ``` -------------------------------- ### Create User and Access Authentication Result Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/firebase-auth.md Example demonstrating how to create a new user with Firebase Authentication and access the authenticated user's email and UID from the result object. ```csharp var authResult = await MauiFIRAuth.CreateUserAsync("user@example.com", "password123"); if (authResult?.User != null) { var email = authResult.User.Email; var userId = authResult.User.Uid; } ``` -------------------------------- ### Session State Monitoring Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/googlecast.md Provides an example of how to monitor the cast session status and update the UI accordingly. ```APIDOC ### Session State Monitoring ```csharp public class CastSessionMonitor { GoogleCastManager castManager; public CastSessionMonitor() { castManager = new GoogleCastManager(); castManager.Configure(); } public void MonitorCastSession() { // Check cast session status periodically var timer = new System.Timers.Timer(1000); timer.Elapsed += (s, e) => { bool isActive = castManager.IsCastSessionActive; OnCastSessionStatusChanged(isActive); }; timer.Start(); } void OnCastSessionStatusChanged(bool isActive) { if (isActive) { Debug.WriteLine("Cast session connected"); EnableCastingUI(); } else { Debug.WriteLine("Cast session disconnected"); DisableCastingUI(); } } void EnableCastingUI() { /* Update UI */ } void DisableCastingUI() { /* Update UI */ } } ``` ``` -------------------------------- ### Firebase Cloud Messaging Setup Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/MANIFEST.md Code for setting up Firebase Cloud Messaging, including token registration and subscription management. ```csharp await MauiFIRMessaging.RegisterAsync(); var token = MauiFIRMessaging.FcmToken; ``` ```csharp await MauiFIRMessaging.UnregisterAsync(); ``` ```csharp await MauiFIRMessaging.SubscribeAsync("news"); ``` ```csharp await MauiFIRMessaging.UnsubscribeAsync("news"); ``` -------------------------------- ### Platform-Specific Initialization Logic Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/overview.md Implement platform-specific initialization logic within a class. This allows for different setup routines for native libraries on iOS and Android, ensuring proper configuration for each environment. ```csharp public class PlatformInitializer { #if IOS public static void Initialize() { MauiFIRApp.AutoConfigure(); } #elif ANDROID public static void Initialize() { FacebookSdk.InitializeSDK(Platform.CurrentActivity, false); } #endif } ``` -------------------------------- ### Integrating with MAUI App Lifecycle Events Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/overview.md Showcases how to integrate native library initialization and analytics flushing into the MAUI application's lifecycle events. This ensures that native functionalities are set up correctly when the app starts and managed during its lifecycle. ```csharp public partial class App : Application { protected override void OnStart() { // Initialize bindings MauiFIRApp.AutoConfigure(); } protected override void OnSleep() { // Flush analytics MauiFIRAnalytics.ResetAnalyticsData(); } } ``` -------------------------------- ### Multi-App Firebase Configuration Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/firebase-app.md Configure multiple Firebase projects or conditional configurations based on the application environment. This example shows how to configure development and production environments separately. ```csharp public class FirebaseManager { public static void ConfigureFirebase(AppEnvironment environment) { #if IOS || MACCATALYST switch (environment) { case AppEnvironment.Development: var devId = "1:111111111:ios:dev0000000000000000"; var devSenderId = "111111111"; MauiFIRApp.Configure(devId, devSenderId); break; case AppEnvironment.Production: var prodId = "1:222222222:ios:prod0000000000000000"; var prodSenderId = "222222222"; MauiFIRApp.Configure(prodId, prodSenderId); break; default: MauiFIRApp.AutoConfigure(); break; } #endif } } ``` -------------------------------- ### Subscribe to Topics for Targeted Notifications Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/firebase-messaging.md Subscribes the device to specific topics to receive targeted notifications. This example shows subscribing based on user status and location. ```csharp // Subscribe to topics for targeted notifications public async Task SubscribeToTopics() { try { // Subscribe to user's interests if (user.IsPremium) { await MauiFIRMessaging.SubscribeAsync("premium_content"); } // Subscribe to location-based topics var location = await GetUserLocation(); await MauiFIRMessaging.SubscribeAsync($"region_{location.Region}"); // Subscribe to general updates await MauiFIRMessaging.SubscribeAsync("general_updates"); } catch (Exception ex) { Debug.WriteLine($"Topic subscription failed: {ex.Message}"); } } ``` -------------------------------- ### Unit Test Pattern for Bindings Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/binding-template.md Provides a basic structure for unit testing C# bindings to native iOS/macOS libraries. It includes examples for testing both instance and static asynchronous methods, with conditional compilation for relevant platforms. ```csharp [TestClass] public class BindingTests { [TestMethod] public void TestStaticMethod() { #if IOS || MACCATALYST var instance = new YourClass(); var result = instance.InstanceMethod("test"); Assert.IsNotNull(result); #endif } [TestMethod] public async Task TestAsyncMethod() { #if IOS || MACCATALYST var result = await YourClass.AsyncMethodAsync(); Assert.IsNotNull(result); #endif } } ``` -------------------------------- ### Build Sample Application Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/binding-template.md Builds the sample application that utilizes the native library binding. ```bash # Build sample application dotnet build sample ``` -------------------------------- ### Get Firebase App Instance ID Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/firebase-analytics.md Asynchronously retrieves the Firebase App Instance ID. This ID is unique to each app installation and is used for various Firebase services. ```csharp try { var appInstanceId = await MauiFIRAnalytics.GetAppInstanceIdAsync(); Debug.WriteLine($"App Instance ID: {appInstanceId}"); } catch (Exception ex) { Debug.WriteLine($"Error getting app instance ID: {ex.Message}"); } ``` -------------------------------- ### SetupWithConfigFilename Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/facebook-sdk.md Initializes the Facebook SDK using a configuration file. The configuration file should be placed in your project and its name provided to this method. ```APIDOC ## SetupWithConfigFilename ### Description Initializes the Facebook SDK using a configuration file. The configuration file should be placed in your project and its name provided to this method. ### Method Static ### Endpoint Not Applicable (SDK Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```csharp FacebookSdk.SetupWithConfigFilename("FacebookConfig"); ``` ### Response #### Success Response void #### Response Example None ``` -------------------------------- ### Usage Examples: Set Firebase Analytics Session Timeout Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/configuration.md These C# code examples show how to set the Firebase Analytics session timeout to 30 minutes (1800 seconds) and 1 hour (3600 seconds). ```csharp // Set 30-minute session timeout MauiFIRAnalytics.SetSessionTimeout(1800); // Set 1-hour session timeout MauiFIRAnalytics.SetSessionTimeout(3600); ``` -------------------------------- ### Build and Run Sample Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/googlecast/README.md Builds and runs the sample application for the Google Cast binding. ```shell dotnet build sample -t:Run ``` -------------------------------- ### Initialize Facebook SDK with Configuration File Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/facebook-sdk.md Initialize the Facebook SDK by providing the path to a configuration file. This is a simple way to set up the SDK with predefined settings. ```csharp FacebookSdk.SetupWithConfigFilename("FacebookConfig"); ``` -------------------------------- ### Get Tenant ID Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/firebase-auth.md Retrieve the tenant ID for multi-tenant applications. This property may be null. ```csharp string tenantId = user.TenantId; ``` -------------------------------- ### SetupWithAppId Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/facebook-sdk.md Initializes the Facebook SDK with explicit app credentials. Provide your Facebook App ID and Client Token to this method. ```APIDOC ## SetupWithAppId ### Description Initializes the Facebook SDK with explicit app credentials. Provide your Facebook App ID and Client Token to this method. ### Method Static ### Endpoint Not Applicable (SDK Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```csharp var appId = NSBundle.MainBundle.ObjectForInfoDictionary("FacebookAppID").ToString(); var clientToken = NSBundle.MainBundle.ObjectForInfoDictionary("FacebookClientToken").ToString(); FacebookSdk.SetupWithAppId(appId, clientToken); ``` ### Response #### Success Response void #### Response Example None ``` -------------------------------- ### Get User ID Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/firebase-auth.md Retrieve the unique identifier for the authenticated user. This property is always available. ```csharp string userId = user.Uid; ``` -------------------------------- ### Run Sample on Android Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/binding-template.md Builds and runs the sample application on an Android device or emulator. ```bash # Run sample on Android dotnet build sample -t:Run -f net9.0-android ``` -------------------------------- ### Firebase Analytics Event Logging Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/MANIFEST.md Examples for logging custom events and user properties with Firebase Analytics. ```csharp await MauiFIRAnalytics.LogEventAsync("tutorial_complete"); ``` ```csharp await MauiFIRAnalytics.SetUserPropertyAsync("user_level", "5"); ``` -------------------------------- ### Build and Run MAUI Sample Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/facebook/README.md Commands to build and run the MAUI sample application for Android and iOS platforms using .NET 9. ```shell dotnet build sample -t:Run -f net9.0-android ``` ```shell dotnet build sample -t:Run -f net9.0-ios ``` -------------------------------- ### Get Phone Number Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/firebase-auth.md Retrieve the user's phone number if it has been provided. This property may be null. ```csharp string phoneNumber = user.PhoneNumber; ``` -------------------------------- ### Run Sample on iOS Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/binding-template.md Builds and runs the sample application on an iOS device or simulator. ```bash # Run sample on iOS dotnet build sample -t:Run -f net9.0-ios ``` -------------------------------- ### Get Refresh Token Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/firebase-auth.md Retrieve the token used to refresh authentication credentials. This property may be null. ```csharp string refreshToken = user.RefreshToken; ``` -------------------------------- ### Initialize Facebook SDK on iOS Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/errors.md Sets up the Facebook SDK for iOS by retrieving the App ID and Client Token from the Info.plist. Handles cases where credentials are not found. ```csharp try { #if IOS var appId = NSBundle.MainBundle.ObjectForInfoDictionary("FacebookAppID")?.ToString(); var clientToken = NSBundle.MainBundle.ObjectForInfoDictionary("FacebookClientToken")?.ToString(); if (string.IsNullOrEmpty(appId) || string.IsNullOrEmpty(clientToken)) { Debug.WriteLine("Facebook credentials not found in Info.plist"); return; } FacebookSdk.SetupWithAppId(appId, clientToken); #endif } catch (Exception ex) { Debug.WriteLine($"Facebook setup error: {ex.Message}"); } ``` -------------------------------- ### Configure Project for NuGet Package Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/binding-template.md Set up your .NET project file to be packable as a NuGet package. Specify target frameworks, package ID, version, and author information. ```xml net9.0-ios;net9.0-maccatalyst true YourCompany.YourBinding 1.0.0 Your Name Native binding for Your Library ``` -------------------------------- ### Log a User Sign-Up Event Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/firebase-analytics.md Log a user sign-up event, optionally including the sign-up method. This helps in analyzing user acquisition channels. ```csharp var signupParams = new NSDictionary("sign_up_method", new NSString("email")); MauiFIRAnalytics.LogEvent("sign_up", signupParams); ``` -------------------------------- ### Get User Email Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/firebase-auth.md Retrieve the user's email address. This property may be null if the email is not available. ```csharp var email = user.Email; ``` -------------------------------- ### Create User Account Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/firebase-auth.md Register a new user with an email address and password. Handles potential exceptions during the creation process. ```csharp try { var authResult = await MauiFIRAuth.CreateUserAsync("newuser@example.com", "SecurePassword123"); if (authResult?.User != null) { Debug.WriteLine($ ``` -------------------------------- ### MauiFIRMessaging.FcmToken Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/firebase-messaging.md Gets the Firebase Cloud Messaging token for the current device. This token is used to send targeted push notifications. ```APIDOC ## MauiFIRMessaging.FcmToken ### Description Gets the Firebase Cloud Messaging token for this device. The token can be null if it's not yet available. ### Property - **FcmToken** (string) - The FCM token or null if not available. ### Example ```csharp var token = MauiFIRMessaging.FcmToken; if (!string.IsNullOrEmpty(token)) { Debug.WriteLine($"FCM Token: {token}"); // Send token to your backend server } else { Debug.WriteLine("FCM token not yet available"); } ``` ``` -------------------------------- ### iOS/macOS Initialization Flow Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/overview.md Illustrates the sequence of events from app launch to Firebase SDK initialization on iOS and macOS. ```text 1. App Launches ↓ 2. App.xaml.cs → MauiFIRApp.AutoConfigure() ↓ 3. Loads GoogleService-Info.plist ↓ 4. Bridges to Swift/ObjC native code ↓ 5. Firebase SDK initializes in native layer ↓ 6. Ready for API calls ``` -------------------------------- ### Build NuGet Package Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/binding-template.md Use the dotnet CLI to build a NuGet package from your binding project. Ensure you specify the correct project path and build configuration. ```bash dotnet pack macios/YourBinding.MaciOS.Binding --configuration Release ``` -------------------------------- ### GetAppInstanceIdAsync Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/firebase-analytics.md Asynchronously retrieves the Firebase App Instance ID. This is useful for identifying unique app installations for analytics purposes. ```APIDOC ## GetAppInstanceIdAsync ### Description Asynchronously retrieves the Firebase App Instance ID. ### Method Static C# method ### Signature `void GetAppInstanceId(Action completion)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **completion** (Action) - Required - Callback with the app instance ID or null ### Response #### Success Response Task (when using async variant) #### Response Example ```csharp try { var appInstanceId = await MauiFIRAnalytics.GetAppInstanceIdAsync(); Debug.WriteLine($"App Instance ID: {appInstanceId}"); } catch (Exception ex) { Debug.WriteLine($"Error getting app instance ID: {ex.Message}"); } ``` ``` -------------------------------- ### Initialize and Log Event with Facebook SDK Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/facebook-sdk.md This snippet demonstrates platform-specific initialization and event logging for the Facebook SDK. Use the iOS/macOS path for Apple platforms and the Android path for Android. Ensure App ID and Client Token are configured in Info.plist for iOS/macOS, and call SetupWithAppId or InitializeSDK accordingly. ```csharp #if IOS || MACCATALYST FacebookSdk.SetupWithAppId(appId, clientToken); FacebookSdk.LogEventWithEventName("AppLaunched"); #elif ANDROID FacebookSdk.InitializeSDK(Platform.CurrentActivity, false); FacebookSdk.LogEvent("AppLaunched"); #endif ``` -------------------------------- ### Firebase App Configuration Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/README.md Provides methods for configuring Firebase services in your MAUI application, including automatic and manual setup options. ```APIDOC ## MauiFIRApp.AutoConfigure() ### Description Automatically configures Firebase services using default settings. ### Method ``` MauiFIRApp.AutoConfigure() ``` ## MauiFIRApp.Configure() ### Description Manually configures Firebase services with custom settings. ### Method ``` MauiFIRApp.Configure() ``` ``` -------------------------------- ### Get Provider ID Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/firebase-auth.md Retrieve the authentication provider ID, such as "password" for email/password authentication. This property may be null. ```csharp if (user.ProviderId == "password") { Debug.WriteLine("User authenticated with email/password"); } ``` -------------------------------- ### Build and Run Firebase Sample Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/firebase/README.md Builds and runs the Firebase sample project targeting net9.0-ios. ```shell dotnet build sample -t:Run -f net9.0-ios ``` -------------------------------- ### Initialize Facebook SDK with Launch Options (iOS/macOS) Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/facebook-sdk.md Use this method in your AppDelegate to notify the Facebook SDK of application launch. It requires the UIApplication instance and optionally accepts launch options. ```csharp using Foundation; using UIKit; using Facebook; public partial class AppDelegate : UIApplicationDelegate { public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) { var success = FacebookSdk.FinishedLaunchingWithApplication(application, launchOptions as NSObject); return success; } } ``` -------------------------------- ### Get User Display Name Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/firebase-auth.md Retrieve the user's display name. Check if the display name is not null or empty before using it. ```csharp if (!string.IsNullOrEmpty(user.DisplayName)) { Debug.WriteLine($"Hello, {user.DisplayName}"); } ``` -------------------------------- ### Advanced Media Casting (Video, Audio, Image) Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/googlecast.md Illustrates how to use the GoogleCastManager to cast different types of media (video, audio, image) with advanced configuration options. Each method checks for an active session before attempting to load media. ```csharp public class MediaCastService { GoogleCastManager castManager; public void CastVideo(MediaContent media) { if (castManager?.IsCastSessionActive ?? false) { castManager.LoadMedia( url: media.VideoUrl, contentType: media.ContentType, title: media.Title, subtitle: media.Description, imageUrl: media.ThumbnailUrl, imageHeight: media.ThumbnailHeight, imageWidth: media.ThumbnailWidth ); } } public void CastAudio(AudioContent audio) { if (castManager?.IsCastSessionActive ?? false) { castManager.LoadMedia( url: audio.AudioUrl, contentType: "audio/mpeg", title: audio.Title, subtitle: audio.Artist, imageUrl: audio.AlbumArtUrl, imageHeight: 300, imageWidth: 300 ); } } public void CastImage(string imageUrl, string title) { if (castManager?.IsCastSessionActive ?? false) { castManager.LoadMedia( url: imageUrl, contentType: "image/jpeg", title: title, subtitle: "Image", imageUrl: imageUrl, imageHeight: 720, imageWidth: 1280 ); } } } ``` -------------------------------- ### Initialize GoogleCastManager in OnAppearing Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/googlecast.md Shows how to initialize the GoogleCastManager when a page appears. This is a common pattern for setting up casting capabilities. Includes a platform-specific permission request for iOS. ```csharp public partial class MainPage : ContentPage { GoogleCastManager? castManager; public MainPage() { InitializeComponent(); } protected override async void OnAppearing() { base.OnAppearing(); if (castManager is null) { castManager = new GoogleCastManager(); castManager.Configure(); #if IOS await Permissions.RequestAsync(); #endif } } } ``` -------------------------------- ### Firebase Configuration Validation Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/firebase-app.md Validate your Firebase configuration by attempting to auto-configure and then verifying that Firebase services, such as Analytics, are accessible. This helps ensure a successful setup. ```csharp public class FirebaseSetup { public static bool ValidateConfiguration() { #if IOS || MACCATALYST try { // Test Firebase configuration MauiFIRApp.AutoConfigure(); // Verify services are accessible var appInstanceId = await MauiFIRAnalytics.GetAppInstanceIdAsync(); if (string.IsNullOrEmpty(appInstanceId)) { Debug.WriteLine("Firebase not properly configured"); return false; } Debug.WriteLine("Firebase configured successfully"); return true; } catch (Exception ex) { Debug.WriteLine($"Firebase configuration error: {ex.Message}"); return false; } #else return true; #endif } } ``` -------------------------------- ### GoogleCastManager.Configure Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/googlecast.md Initializes the Google Cast framework and prepares the casting infrastructure. This method should be called to set up the casting capabilities. ```APIDOC ## GoogleCastManager.Configure ### Description Initializes the Google Cast framework and prepares the casting infrastructure. ### Method void Configure() ### Example ```csharp using GoogleCast; public partial class MainPage : ContentPage { GoogleCastManager? googleCastManager; protected override async void OnAppearing() { base.OnAppearing(); if (googleCastManager is null) { googleCastManager = new GoogleCastManager(); googleCastManager.Configure(); Debug.WriteLine("Google Cast initialized"); } } } ``` ``` -------------------------------- ### Build Android Binding Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/binding-template.md Builds the Android binding project for your native library. ```bash # Build Android binding dotnet build android/YourBinding.Android.Binding ``` -------------------------------- ### Get User Photo URL Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/firebase-auth.md Retrieve the URL for the user's profile photo. This property may be null if no photo is available. The URL is returned as an NSUrl object. ```csharp if (user.PhotoUrl != null) { var profileImageUri = new Uri(user.PhotoUrl.AbsoluteString); } ``` -------------------------------- ### InitializeSDK (Android) Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/facebook-sdk.md Initializes the Facebook SDK for Android. ```APIDOC ## InitializeSDK (Android) ### Description Initializes the Facebook SDK for Android. ### Method Signature `void InitializeSDK(Activity activity, bool isDebug)` ### Parameters - **activity** (Activity) - Required - The current Activity instance - **isDebug** (bool) - Required - Enable debug logging for Facebook SDK ### Example ```csharp #if ANDROID Facebook.FacebookSdk.InitializeSDK(Microsoft.Maui.ApplicationModel.Platform.CurrentActivity, true); #endif ``` ``` -------------------------------- ### Monitor Cast Session State Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/googlecast.md Provides an example of how to monitor the cast session status using a timer. It calls a callback function when the session state changes, allowing for UI updates. ```csharp public class CastSessionMonitor { GoogleCastManager castManager; public CastSessionMonitor() { castManager = new GoogleCastManager(); castManager.Configure(); } public void MonitorCastSession() { // Check cast session status periodically var timer = new System.Timers.Timer(1000); timer.Elapsed += (s, e) => { bool isActive = castManager.IsCastSessionActive; OnCastSessionStatusChanged(isActive); }; timer.Start(); } void OnCastSessionStatusChanged(bool isActive) { if (isActive) { Debug.WriteLine("Cast session connected"); EnableCastingUI(); } else { Debug.WriteLine("Cast session disconnected"); DisableCastingUI(); } } void EnableCastingUI() { /* Update UI */ } void DisableCastingUI() { /* Update UI */ } } ``` -------------------------------- ### Initialize Bindings with Error Handling Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/configuration.md Initializes Firebase, configures analytics session timeout, and sets up messaging for iOS and macOS. Includes error handling to catch and log initialization exceptions, returning a boolean indicating success. ```csharp public static class BindingInitializer { public static async Task InitializeBindingsAsync() { try { #if IOS || MACCATALYST // Initialize Firebase MauiFIRApp.AutoConfigure(); // Configure analytics MauiFIRAnalytics.SetSessionTimeout(1800); // Configure messaging await ConfigureMessagingAsync(); return true; #endif return true; } catch (Exception ex) { Debug.WriteLine($"Initialization error: {ex.Message}"); return false; } } private static async Task ConfigureMessagingAsync() { #if IOS || MACCATALYST var status = await Permissions.CheckStatusAsync(); if (status == PermissionStatus.Granted) { MauiFIRMessaging.IsAutoInitEnabled = true; } #endif } } ``` -------------------------------- ### Integrating with MAUI Permissions and Secure Storage Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/overview.md Demonstrates how to request permissions and access secure storage within a MAUI application. These are common integration points for native library interop. ```csharp // Permissions await Permissions.RequestAsync(); await Permissions.RequestAsync(); // Secure Storage var token = await SecureStorage.GetAsync("fcm_token"); // Connectivity if (Connectivity.Current.ConnectionProfiles.Any()) { // Network available } ``` -------------------------------- ### Get Firebase Cloud Messaging Token Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/firebase-messaging.md Retrieves the Firebase Cloud Messaging token for the device. If the token is not yet available, it will be null. It's recommended to send this token to your backend server. ```csharp var token = MauiFIRMessaging.FcmToken; if (!string.IsNullOrEmpty(token)) { Debug.WriteLine($"FCM Token: {token}"); // Send token to your backend server } else { Debug.WriteLine("FCM token not yet available"); } ``` -------------------------------- ### iOS/macOS Binding Project Configuration Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/configuration.md Set up the .csproj file for an iOS or macOS binding project, specifying target frameworks and binding definitions. ```xml net9.0-ios;net9.0-maccatalyst enable true true ``` -------------------------------- ### Get APNs Token Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/firebase-messaging.md Retrieves the Apple Push Notification Service (APNs) token. This token is necessary for registering with FCM. Note: The actual token is received in AppDelegate.RegisteredForRemoteNotifications or via UNUserNotificationCenter delegates. ```csharp private async Task GetAPNsTokenAsync() { var notificationCenter = UNUserNotificationCenter.Current; var settings = await notificationCenter.GetNotificationSettingsAsync(); if (settings.AuthorizationStatus == UNAuthorizationStatus.Authorized) { UIApplication.SharedApplication.RegisterForRemoteNotifications(); // The token is received in AppDelegate.RegisteredForRemoteNotifications // or via UNUserNotificationCenter delegates } return new NSData(); // Replace with actual token } ``` -------------------------------- ### Use Native Binding Methods in MAUI Page Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/binding-template.md Demonstrates how to call instance and static methods, including asynchronous methods, from a native binding within a MAUI page. Includes basic error handling for exceptions during native calls. ```csharp using YourNamespace; namespace YourSample; public partial class MainPage : ContentPage { public MainPage() { InitializeComponent(); } async void OnButtonClicked(object sender, EventArgs e) { try { #if IOS || MACCATALYST var instance = new YourClass(); instance.InstanceMethod("test"); var result = await YourClass.AsyncMethodAsync(); #endif } catch (Exception ex) { await DisplayAlert("Error", ex.Message, "OK"); } } } ``` -------------------------------- ### Advanced Media Configuration: CastAudio Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/googlecast.md Demonstrates casting audio content with specific parameters. ```APIDOC ### Advanced Media Configuration ```csharp public class MediaCastService { GoogleCastManager castManager; // ... method for casting video ... public void CastAudio(AudioContent audio) { if (castManager?.IsCastSessionActive ?? false) { castManager.LoadMedia( url: audio.AudioUrl, contentType: "audio/mpeg", title: audio.Title, subtitle: audio.Artist, imageUrl: audio.AlbumArtUrl, imageHeight: 300, imageWidth: 300 ); } } // ... other methods for casting images ... } ``` ``` -------------------------------- ### Validate Firebase Configuration Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/errors.md This C# code snippet validates the Firebase configuration by checking for the presence and proper loading of the GoogleService-Info.plist file and attempting Firebase auto-configuration. It's useful for debugging setup issues on iOS and Mac Catalyst platforms. ```csharp public static class ConfigurationValidator { public static bool ValidateFirebaseConfiguration() { #if IOS || MACCATALYST try { var bundle = NSBundle.MainBundle; var bundleId = bundle.BundleIdentifier; Debug.WriteLine($"Bundle ID: {bundleId}"); // Try to load GoogleService-Info.plist var plistPath = bundle.PathForResource("GoogleService-Info", "plist"); if (string.IsNullOrEmpty(plistPath)) { Debug.WriteLine("ERROR: GoogleService-Info.plist not found in bundle"); return false; } Debug.WriteLine($"Plist found at: {plistPath}"); // Try Firebase auto-configuration MauiFIRApp.AutoConfigure(); Debug.WriteLine("Firebase configured successfully"); return true; } catch (Exception ex) { Debug.WriteLine($"Configuration validation failed: {ex.Message}"); Debug.WriteLine($"Stack trace: {ex.StackTrace}"); return false; } #endif return true; } } ``` -------------------------------- ### Load Raw Asset from Application Package Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/facebook/sample/Resources/Raw/AboutAssets.txt This C# code demonstrates how to load a raw asset file named 'AboutAssets.txt' from the application's package using `FileSystem.OpenAppPackageFileAsync`. Ensure the asset is included in the project with the MauiAsset build action. ```csharp async Task LoadMauiAsset() { using var stream = await FileSystem.OpenAppPackageFileAsync("AboutAssets.txt"); using var reader = new StreamReader(stream); var contents = reader.ReadToEnd(); } ``` -------------------------------- ### Configure Environment Settings Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/configuration.md Sets up environment-specific configurations, such as Firebase Project IDs, for development, staging, and production on iOS and macOS. Uses a dictionary to map environment types to project IDs. ```csharp public enum EnvironmentType { Development, Staging, Production } public class EnvironmentConfiguration { private static readonly Dictionary FirebaseProjectIds = new() { { EnvironmentType.Development, "dev-project-id" }, { EnvironmentType.Staging, "staging-project-id" }, { EnvironmentType.Production, "prod-project-id" } }; public static void ConfigureForEnvironment(EnvironmentType env) { #if IOS || MACCATALYST var projectId = FirebaseProjectIds[env]; // Configure based on environment MauiFIRApp.AutoConfigure(); #endif } } ``` -------------------------------- ### Build iOS/macOS Binding Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/binding-template.md Builds the iOS/macOS binding project for your native library. ```bash # Build iOS/macOS binding dotnet build macios/YourBinding.MaciOS.Binding ``` -------------------------------- ### Early App Initialization Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/overview.md Initializes bindings early in the application lifecycle within the `App` constructor. This ensures that native library configurations, like Firebase, are set up before the UI is fully rendered. ```csharp public partial class App : Application { public App() { InitializeComponent(); InitializeBindings(); } private void InitializeBindings() { #if IOS || MACCATALYST MauiFIRApp.AutoConfigure(); #endif } } ``` -------------------------------- ### Error Handling Patterns Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/MANIFEST.md Demonstrates best practices for handling various error conditions that may occur during native library interop. ```csharp try { // Operation that might throw an exception } catch (FirebaseException ex) { // Handle Firebase specific errors Console.WriteLine($"Firebase Error: {ex.Message}"); } catch (Exception ex) { // Handle general errors Console.WriteLine($"General Error: {ex.Message}"); } ``` -------------------------------- ### Advanced Media Configuration: CastVideo Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/googlecast.md Shows how to cast video content with advanced configuration options. ```APIDOC ### Advanced Media Configuration ```csharp public class MediaCastService { GoogleCastManager castManager; public void CastVideo(MediaContent media) { if (castManager?.IsCastSessionActive ?? false) { castManager.LoadMedia( url: media.VideoUrl, contentType: media.ContentType, title: media.Title, subtitle: media.Description, imageUrl: media.ThumbnailUrl, imageHeight: media.ThumbnailHeight, imageWidth: media.ThumbnailWidth ); } } // ... other methods for casting audio and images ... } ``` ``` -------------------------------- ### FinishedLaunchingWithApplication (URL Variant) Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/facebook-sdk.md Handles deep link URLs from Facebook authentication or app link flows. This method should be called when your application receives a URL. ```APIDOC ## FinishedLaunchingWithApplication (URL Variant) ### Description Handles deep link URLs from Facebook authentication or app link flows. This method should be called when your application receives a URL. ### Method Static ### Endpoint Not Applicable (SDK Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```csharp public override bool OpenUrl(UIApplication app, NSUrl url, NSDictionary options) { return FacebookSdk.FinishedLaunchingWithApplication(app, url, null, null); } ``` ### Response #### Success Response - **return** (bool) - Indicates whether the URL was handled. #### Response Example ```json { "return": true } ``` ``` -------------------------------- ### CreateUserAsync Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/firebase-auth.md Creates a new user account with the provided email and password. This is an asynchronous operation. ```APIDOC ## CreateUserAsync ### Description Creates a new user account with email and password. ### Method `void CreateUser(string email, string password, Action callback)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```csharp try { var authResult = await MauiFIRAuth.CreateUserAsync("user@example.com", "password123"); if (authResult?.User != null) { Debug.WriteLine($"User created: {authResult.User.Email}"); Debug.WriteLine($"User ID: {authResult.User.Uid}"); } } catch (Exception ex) { Debug.WriteLine($"Error creating user: {ex.Message}"); } ``` ### Response #### Success Response (200) None #### Response Example None ERROR HANDLING: - Returns: Task (when using async variant) - Throws: NSError if account creation fails ``` -------------------------------- ### FinishedLaunchingWithApplication Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/facebook-sdk.md Notifies the Facebook SDK of application launch with optional launch options. This method is used in the AppDelegate to ensure the SDK is properly initialized upon app startup. ```APIDOC ## FinishedLaunchingWithApplication ### Description Notifies the Facebook SDK of application launch with optional launch options. This method is used in the AppDelegate to ensure the SDK is properly initialized upon app startup. ### Method Static ### Endpoint Not Applicable (SDK Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```csharp using Foundation; using UIKit; using Facebook; public partial class AppDelegate : UIApplicationDelegate { public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) { var success = FacebookSdk.FinishedLaunchingWithApplication(application, launchOptions as NSObject); return success; } } ``` ### Response #### Success Response - **return** (bool) - Indicates success of the operation. #### Response Example ```json { "return": true } ``` ``` -------------------------------- ### Set Up Auth State Listener Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/firebase-auth.md Implement an asynchronous listener to react to changes in the user's authentication state. This is crucial for updating the UI or application logic based on whether a user is signed in or out. ```csharp await MauiFIRAuth.SetAuthStateListenerAsync((user) => { if (user != null) { OnUserSignedIn(user); } else { OnUserSignedOut(); } }); ``` -------------------------------- ### Async/Await Generation for Callbacks Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/overview.md Demonstrates how callback-based Objective-C methods are automatically converted to C# async methods for easier consumption. ```csharp // Original definition with callback [Export("getAppInstanceIdWithCompletion:")] [Async] void GetAppInstanceId(Action completion); // Generated async method Task GetAppInstanceIdAsync(); // Usage var id = await MauiFIRAnalytics.GetAppInstanceIdAsync(); ``` -------------------------------- ### Implementing Error Handling for Sign-In Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/overview.md Implement robust error handling for authentication operations using a `try-catch` block. Log detailed error messages and display user-friendly alerts to inform the user about sign-in failures. ```csharp try { await MauiFIRAuth.SignInAsync(email, password); } catch (Exception ex) { Debug.WriteLine($"Sign in failed: {ex.Message}"); await DisplayAlert("Error", "Sign in failed", "OK"); } ``` -------------------------------- ### Objective-C to C# Method Mapping Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/binding-template.md Demonstrates how to map an Objective-C static method with parameters to its C# equivalent using the [Export] attribute. Usage shows how to call the C# method. ```csharp // Objective-C: +[FacebookSdk logEventWithEventName:parameters:] // C#: [Static] [Export("logEventWithEventName:parameters:")] void LogEventWithEventName(string eventName, NSDictionary parameters); // Usage: FacebookSdk.LogEventWithEventName("event", params); ``` -------------------------------- ### Facebook SDK Integration Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/MANIFEST.md Illustrates integrating the Facebook SDK for MAUI, including initialization and event logging. ```csharp FacebookSdk.InitializeSDK(); ``` ```csharp FacebookSdk.EnableAutoLogAppEvents(); ``` ```csharp FacebookSdk.LogEvent("purchase", parameters); ``` ```csharp FacebookSdk.Flush(); ``` -------------------------------- ### Facebook SDK Initialization for iOS and Android Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/configuration.md Initialize the Facebook SDK using platform-specific methods. For iOS, it retrieves credentials from Info.plist. For Android, it uses the current activity. ```csharp #if IOS var appId = NSBundle.MainBundle.ObjectForInfoDictionary("FacebookAppID").ToString(); var clientToken = NSBundle.MainBundle.ObjectForInfoDictionary("FacebookClientToken").ToString(); FacebookSdk.SetupWithAppId(appId, clientToken); #elif ANDROID FacebookSdk.InitializeSDK(Platform.CurrentActivity, isDebug: false); #endif ``` -------------------------------- ### Initialize Google Cast Framework Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/googlecast.md Call this method to initialize the Google Cast framework. Ensure this is called after the GoogleCastManager instance is created. ```csharp using GoogleCast; public partial class MainPage : ContentPage { GoogleCastManager? googleCastManager; protected override async void OnAppearing() { base.OnAppearing(); if (googleCastManager is null) { googleCastManager = new GoogleCastManager(); googleCastManager.Configure(); Debug.WriteLine("Google Cast initialized"); } } } ``` -------------------------------- ### MauiFIRApp.AutoConfigure Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/firebase-app.md Automatically configures Firebase using the GoogleService-Info.plist configuration file. This is the simplest way to initialize Firebase if you have the configuration file set up correctly. ```APIDOC ## MauiFIRApp.AutoConfigure ### Description Automatically configures Firebase using the GoogleService-Info.plist configuration file. ### Method Static ### Signature ```csharp void AutoConfigure() ``` ### Returns void ### Example ```csharp using Firebase; public partial class App : Application { public App() { InitializeComponent(); // Auto-configure Firebase from GoogleService-Info.plist MauiFIRApp.AutoConfigure(); MainPage = new AppShell(); } } ``` ``` -------------------------------- ### Safe Firebase Initialization with Fallback Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/firebase-app.md Handles Firebase initialization by first attempting auto-configuration for iOS or Mac Catalyst, and then falling back to manual configuration if auto-configuration fails. This ensures Firebase is initialized even if configuration files are missing or malformed. ```csharp public async Task SafeFirebaseInitialization() { try { #if IOS || MACCATALYST // Attempt auto-configuration MauiFIRApp.AutoConfigure(); Debug.WriteLine("Firebase configured from plist"); #endif } catch (Exception ex) { Debug.WriteLine($"Auto-configuration failed: {ex.Message}"); try { // Fallback to manual configuration string fallbackAppId = GetFallbackAppId(); string fallbackSenderId = GetFallbackSenderId(); #if IOS || MACCATALYST MauiFIRApp.Configure(fallbackAppId, fallbackSenderId); Debug.WriteLine("Firebase configured manually"); #endif } catch (Exception fallbackEx) { Debug.WriteLine($"Fallback configuration failed: {fallbackEx.Message}"); await DisplayConfigurationError(); } } } ``` -------------------------------- ### Firebase Configuration Timing and Initialization Source: https://github.com/communitytoolkit/maui.nativelibraryinterop/blob/main/_autodocs/api-reference/firebase-app.md Configure Firebase early in the app lifecycle, such as in the OnStart method, to ensure services like Analytics and Messaging are ready. Includes error handling for initialization failures. ```csharp public partial class App : Application { public App() { InitializeComponent(); } protected override async void OnStart() { // Configure Firebase early in app lifecycle #if IOS || MACCATALYST try { MauiFIRApp.AutoConfigure(); // Initialize other Firebase services await InitializeAnalytics(); await InitializeMessaging(); } catch (Exception ex) { Debug.WriteLine($"Firebase initialization failed: {ex.Message}"); } #endif } private async Task InitializeAnalytics() { MauiFIRAnalytics.SetUserId(GetUserId()); MauiFIRAnalytics.LogEvent("app_started", new NSDictionary()); } private async Task InitializeMessaging() { var token = MauiFIRMessaging.FcmToken; if (!string.IsNullOrEmpty(token)) { await SendTokenToBackend(token); } } } ```