Uploading images to Firebase Storage with Ionic - Part 1

March 2, 2017, 10:32 pm Categories:

Categories

** UPDATED TO IONIC 3 **

In previous tutorials (Part 1 and part 2) I showed you how to use AngularFire2 to integrate firebase content into a simple CRUD (Create, Read, Update & Delete) application using Ionic.

Unfortunately even as great as AngularFire2 is it comes with one VERY serious limitation: images are NOT able to be uploaded to Firebase. This restriction, as you might appreciate, presents certain problems when it comes to considering AngularFire2 for use with real world applications.

Thankfully we can rely on the Firebase Node package to provide such functionality which, through the course of this tutorial, will allow us to build an Ionic application named Moveez that performs the following tasks:

  • Authenticates a user with the firebase service
  • Retrieves a collection of movie records from the database
  • Allows the user to interact with the database to create, amend and delete movie records
  • Upload images and retrieve those for display

Caveat Emptor: this is aimed solely at iOS (as I simply have not had the time to test this on Android) - just so you know ;)

By the end of the tutorial we should end up with an application that resembles something akin to the following screen captures:

Moveez Ionic application screen captures

Got it?

Good! Now let's make a start by setting up Firebase for our application.

Laying the foundation

Navigate to the Firebase website in your browser and, if already registered with the service, log in to your account (if you're not registered then go ahead and create an account, it's free!)

Once logged in you should see all of your existing projects (if you have any) displayed on your account home page like so:

Firebase projects landing page

Let's begin creating a brand new project by selecting the CREATE NEW PROJECT button and, in the modal window that appears, entering your project name and selecting the Country/region from the drop down menu:

Firebase create project

Once your project has been created you can choose how to add Firebase to your application by simply choosing from the following options:

  • Add Firebase to your iOS app
  • Add Firebase to your Android app
  • Add Firebase to your web app

Go ahead and select the Add Firebase to your web app option as this will provide us with the necessary configuration values to integrate Firebase into our Ionic application regardless of platform (I.e web, iOS or Android):

Choose how Firebase will be added to your app

From the modal window that appears, copy the following configuration keys and values:

  • apiKey
  • authDomain
  • databaseURL
  • storageBucket
  • messagingSenderId

Simply copy but do NOT edit these values as you WON'T be able to connect with your Firebase app without them:

Our completed Firebase database

Once copied paste these configuration keys/values into a text file for safekeeping (we'll use these once we create our Ionic project - which will be a little later on in this tutorial).

One final step before we move on - authentication.

We need to ensure that we are 'allowed' to log into our Firebase application from Ionic (or indeed any remote source) by supplying the correct authentication credentials. In order to do this we need to enable an Email/Password sign-in provider and then create the authenticated user.

To do this select the SIGN-IN METHOD tab of the Authentication section and choose the Email/Password Sign-in providers option:

Firebase authentication method

Once this has been enabled select the USERS tab and click on the ADD USER button.

A modal form will then appear allowing you to enter a gmail address and the corresponding password for that account:

Adding a Firebase authenticated user

With our Firebase project now created and the necessary authentication credentials in place we can move onto creating the database and import the necessary data for use in our application.

Creating the database

If you read this tutorial you'll probably realise that I'm a huge advocate of creating your Firebase database structure in JSON and, once completed, uploading and importing that into Firebase.

Approaching the database in this way is a huge time-saver and, in my humble opinion, far easier and more efficient than trying to create the data structure manually from with the Firebase database console itself.

In your preferred code editor enter the following JSON structure and key/value pairs (change the movies to any of your own choosing - if you so desire) and save the file as database.json:

{
   "films" : [
      {
      	 "title" : "John Wick",
      	 "summary": "Ex-assassin John Wick takes down the Russian Mafia in New York",
      	 "date" : "2014",
      	 "duration": "97 minutes",
      	 "rating": "15",
      	 "image" : "none",
      	 "actors" : [
      	    {
      	       "name" : "Keanu Reeves"
      	    },
      	    {
      	       "name" : "Willem Dafoe"
      	    },
      	    {
      	       "name" : "Michael Nyqvist"
      	    },
      	    {
      	       "name" : "Ian McShane"
      	    },
      	    {
      	       "name" : "John Leguizamo"
      	    },
      	    {
      	       "name" : "Bridget Moynahan"
      	    },
      	    {
      	       "name" : "Alfie Allen"
      	    },
      	    {
      	       "name" : "Adrianne Palicki"
      	    }
      	 ],
      	 "genres" : [
      	    {
      	       "name" : "Action"
      	    },
      	    {
      	       "name" : "Thriller"
      	    }
      	 ]
      },
      {
         "title" : "Gladiator",
         "summary": "The general who became a slave, the slave who became a gladiator, the gladiator who defied an empire",
         "date" : "2000",
         "duration": "2hr 29 minutes",
         "rating": "15",
      	 "image" : "none",
         "actors" : [
            {
               "name" : "Russell Crowe"
            },
            {
               "name" : "Oliver Reed"
            },
            {
               "name" : "Joaquin Phoenix"
            },
            {
               "name" : "Connie Nielsen"
            },
            {
               "name" : "Ralf Moeller"
            }
         ],
         "genres" : [
            {
               "name" : "Action"
            },
            {
               "name" : "Historical"
            }
         ]
      },
      {
         "title" : "Catch me if you can",
         "summary": "Frank Abagnale Jr, master of deception",
         "date" : "2002",
         "duration": "135 minutes",
         "rating": "12",
      	 "image" : "none",
         "actors" : [
            {
               "name" : "Tom Hanks"
            },
            {
               "name" : "Leonardo Dicaprio"
            },
            {
               "name" : "Christopher Walken"
            }
         ],
         "genres" : [
            {
               "name" : "Action"
            },
            {
               "name" : "Thriller"
            }
         ]
      }
   ]
}

This is almost the exact same database structure from the previous tutorial except for the addition of the following node:

  • image

No surprises for guessing that this node will be used to store references to an image relating to the film (such as a promotional poster, shot of the lead character or screen capture from a particular scene).

Ready to import the new 'database'?

Of course you are!

Log into your Firebase account and go to your console, select (from the left hand menu) the Database option and, under the Data tab, choose the Import JSON option from the menu consisting of 3 vertical dots like so:

Importing a JSON file into a Firebase database

Now select the database.json file you saved earlier in this section and import that into the database:

Import JSON file to Firebase

As stated earlier, we could have created the database manually, from within the Firebase Database console, but importing a pre-populated JSON structure is a far quicker and more efficient method of setting up the data that we need for our project.

Once the database has been populated it should appear like the following (I've taken the liberty of expanding the final node in the database to reveal the keys/values contained within):

Firebase database with films entries

Databases are essentially nothing more than JSON 'trees' within Firebase and are able to be scaled with far more ease than a traditional SQL data structure. This does however require an understanding of best practice approaches, such as denormalisation, and I would advise any developer not already familiar with Firebase to read this document concerning structuring a database.

With the database now successfully created let's take a moment to look at the Firebase npm plugin.

Firebase Node-how

As mobile/front-end developers where would we honestly be without the Node ecosystem and its incredibly rich plugin repository?

It's almost a given that if you're looking for some pre-built solution for use with a particular software service that the npm registry will help you find what you're looking for - and this is certainly true with our current requirements.

Enter the Firebase JS library which consists of the following key services:

  • firebase-app - The core firebase client
  • firebase-auth - Firebase Authentication
  • firebase-database - The Firebase Realtime Database
  • firebase-storage - Firebase Storage
  • firebase-messaging - Firebase Cloud Messaging

Notice the firebase-storage service? We're going to make extensive use of that during this tutorial along with the core firebase-app client, firebase-database service and, as an added bonus, the firebase-auth service too.

To install the Firebase JS library you would simply run the following command at the root of your Ionic project:

npm install firebase --save

As with most things Node related it's pretty smooth sailing but there is one slight hitch here...as yet we don't actually have an Ionic project!

Hmm, let's set one up and start that ball rolling...

Moveez

In your command line utility (I.e. Terminal in Mac OS X or Command Prompt in Windows) navigate to the root of your projects directory (or wherever you would normally store web/mobile related projects) and run the following:

ionic start moveez blank

This will, once the Ionic CLI has completed running the instruction, create a blank Ionic application which we will need to change into:

cd moveez

Then run the following commands, one after the other upon completion of the previous command, to create the necessary pages and services for the application:

ionic g page Modals
ionic g provider Database
ionic g provider Image
ionic g provider Preloader

We'll leave these for now but explore each one of the above in depth when we start to code the necessary logic for the Moveez application.

If you haven't already installed Type definitions for Firebase to your system then you'll need to run the following command too:

npm install -g typings

The -g flag globally installs the type definitions to our system which is pretty handy as it means they are now available for additional projects as well as our current Moveez project.

This is also especially important as it allows the Ionic CLI transpiler to understand Firebase classes and methods which will be installed as part of the Firebase node package with the following command:

npm install firebase --save

Finally the last item to install will be the Apache Cordova Camera plugin and accompanying Ionic Native package:

ionic cordova plugin add cordova-plugin-camera
npm install --save @ionic-native/camera

This will supply the necessary functionality to capture images, whether by device camera or photolibrary, for inclusion when adding and editing movie entries through our Ionic app.

Before we move onto crafting the logic for our application though we need to make some configuration changes, to the root module and root component.

Rooting the app

Forgetting to configure the application root module is one guaranteed way to trigger compiler errors from the Ionic CLI so it pays to spend a little time getting that right now so we can avoid headaches later!

Open the moveez/src/app/app.module.ts file and make the following amendments:

  • Import Angular's HttpModule and add this to the imports array
  • Import the Image service
  • Import the Preloader service
  • Import the Database service
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';
import { Camera } from '@ionic-native/camera';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { Image } from '../providers/image';
import { Preloader } from '../providers/preloader';
import { Database } from '../providers/database';

@NgModule({
  declarations: [
    MyApp,
    HomePage
  ],
  imports: [
    BrowserModule,
    HttpModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    Camera,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    Image,
    Database,
    Preloader
  ]
})
export class AppModule {}

Finally we also need to import the Firebase node package and add the required Firebase configuration object to the moveez/src/app/app.component.ts like so:

import { Component } from '@angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar, Splashscreen } from 'ionic-native';
import { HomePage } from '../pages/home/home';
import * as firebase from 'firebase';


export const firebaseConfig = {
  apiKey            : 'API-KEY-IS-ENTERED-HERE',
  authDomain        : 'https://console.firebase.google.com/project/YOUR-PROJECT-NAME-HERE',
  databaseURL       : 'https://YOUR-DATABASE-NAME-HERE.firebaseio.com/',
  storageBucket     : 'gs://YOUR-STORAGE-BUCKET-NAME-HERE.appspot.com',
  messagingSenderId : 'YOUR-MESSAGING-SENDER-ID-HERE'
};


@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  rootPage = HomePage;

   constructor(platform: Platform) {
      platform.ready()
      .then(() => 
      {
         // Okay, so the platform is ready and our plugins are available.
         // Here you can do any higher level native things you might need.
         StatusBar.styleDefault();
        Splashscreen.hide();
      });

      firebase.initializeApp(firebaseConfig);
   }
}

Be sure to replace the following:

  • API-KEY-IS-ENTERED-HERE
  • YOUR-PROJECT-NAME-HERE
  • YOUR-DATABASE-NAME-HERE
  • YOUR-STORAGE-BUCKET-NAME-HERE
  • YOUR-MESSAGING-SENDER-ID-HERE

With the exact values found from the Add Firebase to your Web App configuration that you copied during the latter part of the Laying the Foundation section earlier in this tutorial - or you might wonder why your app doesn't work later on!

This concludes part 1 of the tutorial - be sure to join me again in part 2 where we continue with crafting the application logic and upload images to Firebase Storage.

In summary

During this first part of the tutorial we've configured the firebase database, created the foundation for an Ionic project (including the additional pages and services that will be required), installed the necessary node packages, type definitions (if not already installed from a previous project) and Apache Cordova Camera plugin before, finally, configuring our Ionic root module and component.

It may not seem like much but we've set the foundations for our mobile application both from the front-end and the server.

We'll conclude the development of our project and see how Firebase Storage can be integrated into an Ionic application in part 2 of this tutorial.

If you enjoyed what you've read here then please sign up to my mailing list and, if you haven't done so already, take a look at my e-book: Mastering Ionic for information about working with alternative data storage methods in Ionic.

Tags

Categories

Post a comment

All comments are welcome and the rules are simple - be nice and do NOT engage in trolling, spamming, abusiveness or illegal behaviour. If you fail to observe these rules you will be permanently banned from being able to comment.

Top