Introduction
.
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.
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.
Now, Select the Blank App and Choose Portable Class Library (PCL).
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.
Create a project in Firebase
In this step, create a project in Firebase. Go to the following
link.
Click "Add Project".
Now, Give the project name and select your country then Read the terms. Afterward, click "Create project".
Now, your project is ready, click continue.
In this step Choose Storage under the Project Overview.
In this step, you can copy the API URL.
Now, you will change the following Storage Rules Afterward, click "Publish".
Setting up the User Interface
Go to MainPage.Xaml and write the following code.
MainPage.xaml
- <?xml version="1.0" encoding="utf-8" ?>
- <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
- xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
- xmlns:local="clr-namespace:XamarinFirebase"
- x:Class="XamarinFirebase.MainPage">
- <ContentPage.Content>
- <StackLayout HorizontalOptions="CenterAndExpand" VerticalOptions="StartAndExpand">
- <Image x:Name="imgBanner"></Image>
- <Image x:Name="imgChoosed" HeightRequest="200"></Image>
- <Button x:Name="btnPick" Text="Pick" Clicked="btnPick_Clicked"></Button>
- <Button x:Name="btnStore" Text="Store" Clicked="btnStore_Clicked"></Button>
- </StackLayout>
- </ContentPage.Content>
- </ContentPage>
Click the Play button to try it out.
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
Firebase.Storage
Permissions - for Android
In this step give required permissions to your app. The following permissions are a must for this app.
- CAMERA
- READ_EXTERNAL_STORAGE
- WRITE_EXTERNAL_STORAGE
AndroidManifest.xml
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.companyname.XamarinFirebase">
- <uses-sdk android:minSdkVersion="15" />
- <uses-permission android:name="android.permission.CAMERA" />
- <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
- <application android:label="XamarinFirebase.Android">
- <provider android:name="android.support.v4.content.FileProvider" android:authorities="com.companyname.XamarinFirebase.fileprovider" android:exported="false" android:grantUriPermissions="true">
- <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths"></meta-data>
- </provider>
- </application>
- </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
- <?xml version="1.0" encoding="utf-8" ?>
- <paths xmlns:android="http://schemas.android.com/apk/res/android">
- <external-files-path name="my_images" path="Pictures" />
- <external-files-path name="my_movies" path="Movies" />
- </paths>
Pick Image
Now, write the following code to pick an image from your device.
MainPage.xaml.cs
- private async void btnPick_Clicked(object sender, EventArgs e)
- {
- await CrossMedia.Current.Initialize();
- try
- {
- file = await Plugin.Media.CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions
- {
- PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium
- });
- if (file == null)
- return;
- imgChoosed.Source = ImageSource.FromStream(() =>
- {
- var imageStram = file.GetStream();
- return imageStram;
- });
- await StoreImages(file.GetStream());
- }
- catch (Exception ex)
- {
- Debug.WriteLine(ex.Message);
- }
- }
Store Image to Firebase
- private async void btnStore_Clicked(object sender, EventArgs e)
- {
- await StoreImages(file.GetStream());
- }
-
- public async Task<string> StoreImages(Stream imageStream)
- {
- var stroageImage = await new FirebaseStorage("xamarinfirebase-d3352.appspot.com")
- .Child("XamarinMonkeys")
- .Child("image.jpg")
- .PutAsync(imageStream);
- string imgurl = stroageImage;
- return imgurl;
- }
Full Code - MainPage.Xaml.cs
MainPage.Xaml.cs
- using Firebase.Storage;
- using Plugin.Media;
- using Plugin.Media.Abstractions;
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.IO;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using Xamarin.Forms;
-
- namespace XamarinFirebase
- {
- public partial class MainPage : ContentPage
- {
- MediaFile file;
- public MainPage()
- {
- InitializeComponent();
-
- imgBanner.Source = ImageSource.FromResource("XamarinFirebase.images.banner.png");
- imgChoosed.Source = ImageSource.FromResource("XamarinFirebase.images.default.jpg");
- }
-
- private async void btnPick_Clicked(object sender, EventArgs e)
- {
- await CrossMedia.Current.Initialize();
- try
- {
- file = await Plugin.Media.CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions
- {
- PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium
- });
- if (file == null)
- return;
- imgChoosed.Source = ImageSource.FromStream(() =>
- {
- var imageStram = file.GetStream();
- return imageStram;
- });
- await StoreImages(file.GetStream());
- }
- catch (Exception ex)
- {
- Debug.WriteLine(ex.Message);
- }
- }
-
- private async void btnStore_Clicked(object sender, EventArgs e)
- {
- await StoreImages(file.GetStream());
- }
-
- public async Task<string> StoreImages(Stream imageStream)
- {
- var stroageImage = await new FirebaseStorage("xamarinfirebase-d3352.appspot.com")
- .Child("XamarinMonkeys")
- .Child("image.jpg")
- .PutAsync(imageStream);
- string imgurl = stroageImage;
- return imgurl;
- }
- }
- }
Click the Play button to try it out.
I hope you have understood how to use Firebase Storage in Xamarin.Forms.
Thanks for reading. Please share comments and feedback.