Xamarin.Forms - Working With Firebase Storage

Introduction

 
Xamarin.

Forms code runs on multiple platforms - each of which has its own filesystem. This means that reading and writing files are the most easily done tasks using native file APIs on each platform. Alternatively, embedded resources are also a simpler solution to distribute the data files with an app.

Firebase

Firebase gives you functionality like analytics, databases, messaging and crash reporting so you can move quickly and focus on your users.
 Xamarin
 
Firebase is a backend platform for building Web, Android, and iOS applications. It offers real-time database, different APIs, multiple authentication types and hosting platform. 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
  • Notifications
  • Authentication
  • Hosting
For more information

Prerequisites
  • Visual Studio 2017(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.

Choose the Cross-platform App project under Visual C#-->Cross-platform in the New Project dialog.

Xamarin 

Now, Select the Blank App and Choose Portable Class Library (PCL).
 
Xamarin
 
Subsequently, go to the solution. In there, you get all the files and sources of your project (PCL). 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

Create a project in Firebase

In this step, create a project in Firebase. Go to the following link.

Click "Add Project".

Xamarin 

Now, Give the project name and select your country then Read the terms. Afterward, click "Create project".

Xamarin 
 
Now, your project is ready, click continue.

Xamarin 
 
In this step Choose Storage under the Project Overview.

Xamarin 
 
In this step, you can copy the API URL.

Xamarin 

Now, you will change the following Storage Rules Afterward, click "Publish".

Xamarin 

Setting up the User Interface

Go to MainPage.Xaml and write the following code.

MainPage.xaml
 
Xamarin
  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.     <ContentPage.Content>  
  7.         <StackLayout HorizontalOptions="CenterAndExpand" VerticalOptions="StartAndExpand">  
  8.             <Image x:Name="imgBanner"></Image>  
  9.             <Image x:Name="imgChoosed" HeightRequest="200"></Image>  
  10.             <Button x:Name="btnPick" Text="Pick" Clicked="btnPick_Clicked"></Button>  
  11.             <Button x:Name="btnStore" Text="Store" Clicked="btnStore_Clicked"></Button>  
  12.         </StackLayout>  
  13.     </ContentPage.Content>  
  14. </ContentPage> 
Click the Play button to try it out.
 
Xamarin 
 
NuGet Packages

Now, add the following NuGet Packages.
  • Xam.Plugin.Media
  • Firebase.Storage
Go to Solution Explorer and select your solution. Right-click and select "Manage NuGet Packages for Solution".

Xam.Plugin.Media
 
Xamarin 
 
Firebase.Storage
 
Xamarin 

Permissions - for Android


In this step give required permissions to your app. The following permissions are a must for this app.
  1. CAMERA
  2. READ_EXTERNAL_STORAGE
  3. WRITE_EXTERNAL_STORAGE
AndroidManifest.xml
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.companyname.XamarinFirebase">  
  3.     <uses-sdk android:minSdkVersion="15" />  
  4.     <uses-permission android:name="android.permission.CAMERA" />    
  5.     <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />    
  6.     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />   
  7.     <application android:label="XamarinFirebase.Android">  
  8.     <provider android:name="android.support.v4.content.FileProvider" android:authorities="com.companyname.XamarinFirebase.fileprovider" android:exported="false" android:grantUriPermissions="true">    
  9.         <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths"></meta-data>    
  10.     </provider>    
  11.   </application>  
  12. </manifest>  
In this step, create a xml file under Resource-->xml folder for get file paths.

Go to Solution—>Android —>Right click—>New—>Xml—> file_paths.xml

Now, write the following code to get file paths.

file_paths.xml
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <paths xmlns:android="http://schemas.android.com/apk/res/android">  
  3.   <external-files-path name="my_images" path="Pictures" />  
  4.   <external-files-path name="my_movies" path="Movies" />  
  5. </paths>  
Pick Image

Now, write the following code to pick an image from your device.

MainPage.xaml.cs

  1. private async void btnPick_Clicked(object sender, EventArgs e)  
  2.         {  
  3.             await CrossMedia.Current.Initialize();  
  4.             try  
  5.             {  
  6.                 file = await Plugin.Media.CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions  
  7.                 {  
  8.                     PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium  
  9.                 });  
  10.                 if (file == null)  
  11.                     return;  
  12.                 imgChoosed.Source = ImageSource.FromStream(() =>  
  13.                 {  
  14.                    var imageStram = file.GetStream();  
  15.                     return imageStram;  
  16.                 });  
  17.                 await StoreImages(file.GetStream());  
  18.             }  
  19.             catch (Exception ex)  
  20.             {  
  21.                 Debug.WriteLine(ex.Message);  
  22.             }  
  23.         }  
Store Image to Firebase
  1. private async void btnStore_Clicked(object sender, EventArgs e)  
  2.         {  
  3.             await StoreImages(file.GetStream());  
  4.         }  
  5.   
  6.         public async Task<string> StoreImages(Stream imageStream)  
  7.         {  
  8.             var stroageImage = await new FirebaseStorage("xamarinfirebase-d3352.appspot.com")  
  9.                 .Child("XamarinMonkeys")  
  10.                 .Child("image.jpg")  
  11.                 .PutAsync(imageStream);  
  12.             string imgurl = stroageImage;  
  13.             return imgurl;  
  14.         }  
Full Code - MainPage.Xaml.cs

MainPage.Xaml.cs

  1. using Firebase.Storage;  
  2. using Plugin.Media;  
  3. using Plugin.Media.Abstractions;  
  4. using System;  
  5. using System.Collections.Generic;  
  6. using System.Diagnostics;  
  7. using System.IO;  
  8. using System.Linq;  
  9. using System.Text;  
  10. using System.Threading.Tasks;  
  11. using Xamarin.Forms;  
  12.   
  13. namespace XamarinFirebase  
  14. {  
  15.     public partial class MainPage : ContentPage  
  16.     {  
  17.         MediaFile file;  
  18.         public MainPage()  
  19.         {  
  20.             InitializeComponent();  
  21.   
  22.             imgBanner.Source = ImageSource.FromResource("XamarinFirebase.images.banner.png");  
  23.             imgChoosed.Source = ImageSource.FromResource("XamarinFirebase.images.default.jpg");  
  24.         }  
  25.   
  26.         private async void btnPick_Clicked(object sender, EventArgs e)  
  27.         {  
  28.             await CrossMedia.Current.Initialize();  
  29.             try  
  30.             {  
  31.                 file = await Plugin.Media.CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions  
  32.                 {  
  33.                     PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium  
  34.                 });  
  35.                 if (file == null)  
  36.                     return;  
  37.                 imgChoosed.Source = ImageSource.FromStream(() =>  
  38.                 {  
  39.                    var imageStram = file.GetStream();  
  40.                     return imageStram;  
  41.                 });  
  42.                 await StoreImages(file.GetStream());  
  43.             }  
  44.             catch (Exception ex)  
  45.             {  
  46.                 Debug.WriteLine(ex.Message);  
  47.             }  
  48.         }  
  49.   
  50.         private async void btnStore_Clicked(object sender, EventArgs e)  
  51.         {  
  52.             await StoreImages(file.GetStream());  
  53.         }  
  54.   
  55.         public async Task<string> StoreImages(Stream imageStream)  
  56.         {  
  57.             var stroageImage = await new FirebaseStorage("xamarinfirebase-d3352.appspot.com")  
  58.                 .Child("XamarinMonkeys")  
  59.                 .Child("image.jpg")  
  60.                 .PutAsync(imageStream);  
  61.             string imgurl = stroageImage;  
  62.             return imgurl;  
  63.         }  
  64.     }  
  65. }  
Click the Play button to try it out.

Xamarin 
 
Xamarin 
 
I hope you have understood how to use Firebase Storage in Xamarin.Forms.

Thanks for reading. Please share comments and feedback.