Xamarin.Forms - Working With Firebase Storage CRUD Operations

Introduction
Xamarin.Forms - Working With Firebase Storage CRUD Operations
 
Xamarin.Forms code runs on multiple platforms - each of which has its own filesystem. This means that reading and writing files is most easily done using the native file APIs on each platform. Alternatively, embedded resources are a simpler solution to distribute data files with an app. You can read my previous article here to learn about Firebase CRUD operations.
Firebase
 
Firebase gives you functionality like analytics, databases, messaging, and crash reporting so you can move quickly and focus on your users.
 
Xamarin.Forms - Working With Firebase Storage CRUD Operations
 
Firebase is a back-end platform for building Web, Android, and iOS applications. It offers real-time database, different APIs, multiple authentication types, and hosting platforms. This is an introductory tutorial which covers the basics of the Firebase platform and explains how to deal with its various components and sub-components.
 
Build apps with Firebase
  • Real-time Database
  • Storage
  • Notifications
  • Authentication
  • Hosting
Prerequisites
  • Visual Studio 2017 or Later (Windows or Mac)
Setting up a Xamarin.Forms Project
 
Start by creating a new Xamarin.Forms project. You’ll learn more by going through the steps yourself, however, you can download the source code from here - https://github.com/susairajs/Xamarin-Firebase-Storage
 
Visual Studio 2019 has more options in the opening window. Clone or check out the code from any repository or open a project or solution for your computer.
 
Now, you need to click "Create a new project".
 
Xamarin.Forms - Working With Firebase Storage CRUD Operations 
 
Now, filter by Project Type: Mobile
 
Choose the Mobile App (Xamarin. forms) project under C# and Mobile.
 
Xamarin.Forms - Working With Firebase Storage CRUD Operations 
 
Name your app. You probably want your project and solution to use the same name as your app. Put it on your preferred location for projects and click "Create".
 
Xamarin.Forms - Working With Firebase Storage CRUD Operations 
 
Now, select the blank app and target platforms - Android, iOS, and Windows (UWP).
 
Xamarin.Forms - Working With Firebase Storage CRUD Operations
 
Subsequently, go to the solution. In there, you get all the files and sources of your project (.NET Standard). Now, select XAML page and double-click to open the MainPage.Xaml page.
 
You now have a basic Xamarin.Forms app. Click the "Play" button to try it out.
 
Xamarin.Forms - Working With Firebase Storage CRUD Operations
 
Create a project in Firebase
 
In this step, create a project in Firebase. Go to the following link.
 
https://console.firebase.google.com/
 
Click "Add Project".
 
Xamarin.Forms - Working With Firebase Storage CRUD Operations 
 
Now, give the project a name and select your country; then read the terms. Afterward, click "Create project".
 
Xamarin.Forms - Working With Firebase Storage CRUD Operations
 
Now, your project is ready; click "Continue".
 
Xamarin.Forms - Working With Firebase Storage CRUD Operations
 
In this step, choose Storage under the Project Overview.
 
Xamarin.Forms - Working With Firebase Storage CRUD Operations
 
Now, you need to change the following Storage Rules. Afterward, click "Publish".
  1. service firebase.storage {  
  2.   match /b/{bucket}/o {  
  3.     match /{allPaths=**} {  
  4.       allow read, write: if request.auth == null;  
  5.     }  
  6.   }  
  7. }  
Xamarin.Forms - Working With Firebase Storage CRUD Operations
 
Now, your Firebase Storage is ready. You can use your Storage API URI here.
 
Xamarin.Forms - Working With Firebase Storage CRUD Operations 
 
Setting up the User Interface
 
Go to MainPage.Xaml and write the following code.
 
MainPage.xaml
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"  
  3.              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"  
  4.              xmlns:local="clr-namespace:XamarinFirebase"  
  5.              x:Class="XamarinFirebase.MainPage">  
  6.   
  7.     <StackLayout>  
  8.         <StackLayout>  
  9.             <StackLayout HorizontalOptions="Center" VerticalOptions="Start">  
  10.                 <Image x:Name="imgBanner" Source="banner.png" ></Image>  
  11.                 <Image Margin="0,0,0,10" HeightRequest="100" Source="firebase.png" ></Image>  
  12.                 <Label Margin="0,0,0,10" Text="Firebase Storage" FontAttributes="Bold" FontSize="Large" TextColor="Gray" HorizontalTextAlignment="Center" ></Label>  
  13.                 <Image x:Name="imgChoosed" HeightRequest="150"></Image>  
  14.                 <Entry x:Name="txtFileName" Placeholder="Enter FileName"></Entry>  
  15.                 <StackLayout  HorizontalOptions="CenterAndExpand" Orientation="Horizontal">  
  16.                     <Button x:Name="btnPick" WidthRequest="200" Text="Pick" Clicked="BtnPick_Clicked"/>  
  17.                     <Button x:Name="btnUpload" WidthRequest="200" Text="Upload" Clicked="BtnUpload_Clicked" />  
  18.                 </StackLayout>  
  19.                 <StackLayout HorizontalOptions="CenterAndExpand" Orientation="Horizontal">  
  20.                     <Button x:Name="btnDownload" WidthRequest="200" Text="Download" Clicked="BtnDownload_Clicked" />  
  21.                     <Button x:Name="btnDelete" WidthRequest="200" Text="Delete" Clicked="BtnDelete_Clicked" />  
  22.                 </StackLayout>  
  23.                 <Label x:Name="lblPath"></Label>  
  24.                   
  25.             </StackLayout>  
  26.         </StackLayout>  
  27.     </StackLayout>  
  28.   
  29. </ContentPage>  
Click the "Play" button to try it out.
 
Xamarin.Forms - Working With Firebase Storage CRUD Operations
 
NuGet Packages
 
Now, add the following NuGet packages.
  1. Xam.Plugin.Media
  2. Firebase.Storage
Add FirebaseDatabase.net NuGet
 
Go to Solution Explorer and select your solution. Right-click and select "Manage NuGet Packages for Solution". Search for "FirebaseDatabase.net" and add the resultant package. Remember to install it for each project (.NET Standard, Android, iOS, and UWP).
 
Xamarin.Forms - Working With Firebase Storage CRUD Operations
 
Connect Firebase
 
Now, write the following code to connect to your Firebase Storage.
  1. using Firebase.Storage;  
  2.   
  3. FirebaseStorage firebaseStorage = new FirebaseStorage("xamarinfirebase-****.appspot.com");  
Upload
 
Now, write the code to upload a file to Firebase Storage.
 
FirebaseStorageHelper.cs
  1. public async Task<string> UploadFile(Stream fileStream,string fileName)  
  2.         {  
  3.             var imageUrl = await firebaseStorage  
  4.                 .Child("XamarinMonkeys")  
  5.                 .Child(fileName)  
  6.                 .PutAsync(fileStream);  
  7.             return imageUrl;  
  8.         }  
MainPage.Xaml.cs
  1. FirebaseStorageHelper firebaseStorageHelper = new FirebaseStorageHelper();  
  2.         MediaFile file;  
  3.         public MainPage()  
  4.         {  
  5.             InitializeComponent();  
  6.         }  
  7.   
  8.         protected async override void OnAppearing()  
  9.         {  
  10.   
  11.             base.OnAppearing();  
  12.               
  13.         }  
  14.           
  15. private async void BtnPick_Clicked(object sender, EventArgs e)  
  16.         {  
  17.             await CrossMedia.Current.Initialize();  
  18.             try  
  19.             {  
  20.                 file = await Plugin.Media.CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions  
  21.                 {  
  22.                     PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium  
  23.                 });  
  24.                 if (file == null)  
  25.                     return;  
  26.                 imgChoosed.Source = ImageSource.FromStream(() =>  
  27.                 {  
  28.                     var imageStram = file.GetStream();  
  29.                     return imageStram;  
  30.                 });  
  31.             }  
  32.             catch (Exception ex)  
  33.             {  
  34.                 Debug.WriteLine(ex.Message);  
  35.             }  
  36.         }  
  37.   
  38.         private async void BtnUpload_Clicked(object sender, EventArgs e)  
  39.         {  
  40.             await firebaseStorageHelper.UploadFile(file.GetStream(), Path.GetFileName(file.Path));  
  41.         }   
Click the "Play" button to try it out.
 
Xamarin.Forms - Working With Firebase Storage CRUD Operations
 
Xamarin.Forms - Working With Firebase Storage CRUD Operations 
 
Download
 
Now, write the following code to download the file from Firebase Storage.
  1. public async Task<string> GetFile(string fileName)  
  2.         {  
  3.             return await firebaseStorage  
  4.                 .Child("XamarinMonkeys")  
  5.                 .Child(fileName)  
  6.                 .GetDownloadUrlAsync();  
  7.         }  
  8.   
  9. private async void BtnDownload_Clicked(object sender, EventArgs e)  
  10.         {  
  11.             string path = await firebaseStorageHelper.GetFile(txtFileName.Text);  
  12.             if (path != null)  
  13.             {  
  14.                 lblPath.Text = path;  
  15.                 await DisplayAlert("Success", path, "OK");  
  16.             }  
  17.               
  18.         }   
Click the "Play" button to try it out.
 
Xamarin.Forms - Working With Firebase Storage CRUD Operations
 
Delete
 
Now, write the following code to delete the file from Firebase Storage.
  1. public async Task DeleteFile(string fileName)  
  2.         {  
  3.            await firebaseStorage  
  4.                 .Child("XamarinMonkeys")  
  5.                 .Child(fileName)  
  6.                 .DeleteAsync();  
  7.               
  8.         }  
  9.   
  10.  private async void BtnDelete_Clicked(object sender, EventArgs e)  
  11.         {  
  12.             await firebaseStorageHelper.DeleteFile(txtFileName.Text);  
  13.             lblPath.Text = string.Empty;  
  14.             await DisplayAlert("Success""Deleted""OK");  
  15.         }  
Click the "Play" button to try it out.
 
Xamarin.Forms - Working With Firebase Storage CRUD Operations
 
Xamarin.Forms - Working With Firebase Storage CRUD Operations 
 
Full code - FirebaseStorageHelper.cs 
  1. using System.Threading.Tasks;  
  2. using Firebase.Storage;  
  3.   
  4. namespace XamarinFirebase.Helper  
  5. {  
  6.   
  7.     public class FirebaseStorageHelper  
  8.     {  
  9.         FirebaseStorage firebaseStorage = new FirebaseStorage("xamarinfirebase-****.appspot.com");  
  10.   
  11.         public async Task<string> UploadFile(Stream fileStream,string fileName)  
  12.         {  
  13.             var imageUrl = await firebaseStorage  
  14.                 .Child("XamarinMonkeys")  
  15.                 .Child(fileName)  
  16.                 .PutAsync(fileStream);  
  17.             return imageUrl;  
  18.         }  
  19.   
  20.         public async Task<string> GetFile(string fileName)  
  21.         {  
  22.             return await firebaseStorage  
  23.                 .Child("XamarinMonkeys")  
  24.                 .Child(fileName)  
  25.                 .GetDownloadUrlAsync();  
  26.         }  
  27.         public async Task DeleteFile(string fileName)  
  28.         {  
  29.            await firebaseStorage  
  30.                 .Child("XamarinMonkeys")  
  31.                 .Child(fileName)  
  32.                 .DeleteAsync();  
  33.               
  34.         }  
  35.     }  
  36. }  
MainPage.Xaml.cs
  1. using XamarinFirebase.Helper;  
  2. using XamarinFirebase.Model;  
  3. using Plugin.Media;  
  4. using Plugin.Media.Abstractions;  
  5. using System.Diagnostics;  
  6. using System.IO;  
  7.   
  8. namespace XamarinFirebase  
  9. {  
  10.     public partial class MainPage : ContentPage  
  11.     {  
  12.         FirebaseStorageHelper firebaseStorageHelper = new FirebaseStorageHelper();  
  13.         MediaFile file;  
  14.         public MainPage()  
  15.         {  
  16.             InitializeComponent();  
  17.         }  
  18.   
  19.         protected async override void OnAppearing()  
  20.         {  
  21.   
  22.             base.OnAppearing();  
  23.               
  24.         }  
  25.           
  26.   
  27.         private async void BtnPick_Clicked(object sender, EventArgs e)  
  28.         {  
  29.             await CrossMedia.Current.Initialize();  
  30.             try  
  31.             {  
  32.                 file = await Plugin.Media.CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions  
  33.                 {  
  34.                     PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium  
  35.                 });  
  36.                 if (file == null)  
  37.                     return;  
  38.                 imgChoosed.Source = ImageSource.FromStream(() =>  
  39.                 {  
  40.                     var imageStram = file.GetStream();  
  41.                     return imageStram;  
  42.                 });  
  43.             }  
  44.             catch (Exception ex)  
  45.             {  
  46.                 Debug.WriteLine(ex.Message);  
  47.             }  
  48.         }  
  49.   
  50.         private async void BtnUpload_Clicked(object sender, EventArgs e)  
  51.         {  
  52.             await firebaseStorageHelper.UploadFile(file.GetStream(), Path.GetFileName(file.Path));  
  53.         }  
  54.         private async void BtnDelete_Clicked(object sender, EventArgs e)  
  55.         {  
  56.             await firebaseStorageHelper.DeleteFile(txtFileName.Text);  
  57.             lblPath.Text = string.Empty;  
  58.             await DisplayAlert("Success""Deleted""OK");  
  59.         }  
  60.   
  61.         private async void BtnDownload_Clicked(object sender, EventArgs e)  
  62.         {  
  63.             string path = await firebaseStorageHelper.GetFile(txtFileName.Text);  
  64.             if (path != null)  
  65.             {  
  66.                 lblPath.Text = path;  
  67.                 await DisplayAlert("Success", path, "OK");  
  68.             }  
  69.               
  70.         }  
  71.   
  72.           
  73.     }  
  74. }  
I hope you have understood how to upload, download, and delete a file using Firebase Storage in Xamarin.Forms. Thanks for reading.
 
Please share your comments and feedback.
 
Happy Coding :)


Similar Articles