Skip to main content
← Blog
Desarrollo

Firebase for Xamarin.Forms — Part 4: FirebaseDatabase for iOS

2 min read
Firebase for Xamarin.Forms — Part 4: FirebaseDatabase for iOS

After implementing FirebaseDB for Android, we wrap up this Firebase Xamarin.Forms series with the iOS database implementation.

Adding the NuGet package

Search for and install Xamarin.Firebase.iOS.Database in your iOS project.

Configuring the iOS build

Firebase Database on iOS requires a small build configuration tweak. Open your iOS project’s Build Options and find the Additional mtouch arguments field. Add:

--registrar:static

The Firebase configuration itself (credentials, database URL) is already handled by GoogleService-Info.plist that we set up in Part 2, so no code changes are needed there.

iOS service implementation

Create the iOS FirebaseDBService implementing IFirebaseDBService:

Connect

DatabaseReference databaseReference;

public void Connect() {
    databaseReference = Database.DefaultInstance.GetRootReference();
}

GetMessage

public void GetMessage() {
    var userId = authService.GetUserId();
    var messages = databaseReference.GetChild("messages").GetChild(userId);

    nuint handleReference = messages.ObserveEvent(DataEventType.Value, (snapshot) => {
        String message = "";
        if (snapshot.GetValue() != NSNull.Null) {
            message = snapshot.GetValue().ToString();
        }
        MessagingCenter.Send(FirebaseDBService.KEY_MESSAGE,
                             FirebaseDBService.KEY_MESSAGE,
                             message);
    });
}

SetMessage

public void SetMessage(String message) {
    var userId = authService.GetUserId();
    var messages = databaseReference.GetChild("messages").GetChild(userId);
    messages.SetValue<NSString>((Foundation.NSString)message);
}

The iOS implementation closely mirrors the Android one — the main difference is using ObserveEvent with a closure instead of a separate ValueEventListener class.

What we’ve covered

Looking back at the full series:

  1. Introduction — Firebase overview and what we’d build
  2. Part 1 — Firebase Auth for Android (email/password + Google)
  3. Part 2 — Firebase Auth for iOS (email/password + Google via Xamarin.Auth)
  4. Part 3 — Firebase Realtime Database for Android
  5. Part 4 — Firebase Realtime Database for iOS (this article)

It’s a small project, but it covers the full authentication and database loop on both platforms. Use it as a foundation for your own Xamarin.Forms apps that need Firebase.

Full source code: https://github.com/jamontes79/xamarin-forms-firebase-sample


More in Desarrollo