React Native Image Upload To Firebase Cloud Storage — iOS

Emery Muhozi
Backticks & Tildes
Published in
7 min readApr 16, 2019

In this tutorial, we will go through how to upload images to Firebase Cloud Storage in React Native applications.

React Native

React Native is a Javascript framework by Facebook used to build cross mobile native applications(iOS, Android, and Windows). We will build an example app for iOS. You can read more about React Native here.

Firebase

Firebase is a web and mobile development platform by Firebase Inc owned by Google. It has a lot of services you can use including real-time database, file storage service, and so many others. We’ll use Firebase Storage services to store images in our application.

Prerequisites

Before continuing the tutorial, let’s make sure that we have already set up the React Native environment. If not, follow the guide here.

For iOS, we will use Cocoapods. CocoaPods is a dependency manager for Swift and Objective-C Cocoa projects. CocoaPods can help you scale your projects elegantly and ease dependency management.

Initialize the application

react-native init RnFirebaseImgUpload

After initializing the React Native application, create a dependencies file for iOS: ios/Podfile and remember to add ios/Pods in your .gitignore

Then add the following in your Podfile

After adding Podfile, install the dependencies using Cocoapod by running from the iOS folder of the project(RnFirebaseImgUpload/ios):

pod install

From now on, we will be using RnFirebaseImgUpload.xcworkspace to open our project in XCode instead of usual RnFirebaseImgUpload.xcodeproj . RnFirebaseImgUpload.xcworkspace get generated when you run pod install .

Read more about using Cocoapod with React Native here.

We will use the following React Native packages, thanks to their creators and contributors:

Integrate Firebase in our iOS app

Log in or create an account on Firebase if you don’t have one, then create a project. After creating a project, register an app for iOS and Android to get the token.

  1. Install Firebase core dependency

For iOS, you must provide the bundle name.

Register Firebase app for iOS

We can use XCode to get our iOS app bundle name by selecting our project on the sidebar in general and see bundle identifier input. You can also customize the bundle name from there.

In the next step, we download our app config file(GoogleService-Info.plist) and copy it into our project folder. In our case, we’ll copy it to RnFirebaseImgUpload/ios/RnFirebaseImgUpload

Download app config file

Next, We add Firebase core dependency in our dependencies file (Podfile). Here, We will ignore other steps which we don’t have to follow as we are using React Native.

pod 'Folly', :podspec => '../node_modules/react-native/third-party-podspecs/Folly.podspec'
...
# Firebase core dependency
pod 'Firebase/Core
end

After adding the dependency run move to anios folder of the app and run the following command to update the dependencies:

pod update

2. Configure Firebase

Add pod ‘Firebase/Storage’, ‘~> 5.15.0’ in our dependency file(Podfile )

pod 'Folly', :podspec => '../node_modules/react-native/third-party-podspecs/Folly.podspec'
...
# Firebase core dependency
pod 'Firebase/Core'
# Firebase storage dependency
pod 'Firebase/Storage', '~> 5.15.0'
end

Don’t forget to update the dependencies by running the following command again:

pod update

3. Initialize Firebase

To initialize Firebase in our existing ios app, we will add the following line in AppDelegate.m Which is located in RnFirebaseImgUpload/ios/RnFirebaseImgUpload/ and add the highlighted lines below:

...#import <React/RCTRootView.h>
#import <Firebase.h> // Import firebase
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[FIRApp configure]; // Configure firebase
NSURL *jsCodeLocation;
...

The above step is almost the same as the iOS Firebase integration step found in the Firebase guide (Note that React Native use Objective-c):

4. Install React Native Firebase

React Native Firebase is a light-weight Javascript layer connecting you to the native Firebase SDKs for both iOS and Android. It aims to mirror the official Firebase Web SDK as closely as possible.

npm install react-native-firebase

Link react-native-firebase

react-native link react-native-firebase

5. Test our Firebase integration

It’s now time to test our integration. Open XCode and stop the application if it was running, then run the application again.

If the app was successfully launched in the emulator, add the following lines in App.js to test our integration:

import React, {Component} from 'react';
import {StyleSheet, Text, View} from 'react-native';
import firebase from 'react-native-firebase';
const { app } = firebase.storage();export default class App extends Component<Props> {
render() {
alert(JSON.stringify(app));
return (
<View style={styles.container}>
....

After adding the above lines of code, go in the emulator and press Cmd+R to reload.

After reloading the application, we should see our Firebase application details

This step corresponds to the fifth step of the official Firebase iOS integration of verifying the installation.

Verifying the installation

Install react-native-image-picker

React Native Image Picker is a React Native module that allows you to select an image from the device images library or directly from the camera. This module will help us to pick an image that will be sent to our Firebase Storage Bucket.

  1. Installation

To install React Native Image Picker is straight forward:

npm install react-native-image-picker

Link the package: react-native link react-native-image-picker , this will add this module in our dependencies, Podfile : pod 'react-native-image-picker', : path => ‘../node_modules/react-native-image-picker’

After that, we update our dependencies by running pod update (Make sure that you are in the iOS folder) and rerun the application from XCode.

2. Test if our image picker works

Let’s customize our App.js and add the following code:

The above code will give us the following output:

Image Picker

Upload image to the Firebase Cloud Storage

So far, we successfully integrated firebase and React Native Image Picker in our iOS app. Next, we have to send the picked image to the Firebase Bucket.

  1. Set up Firebase storage permission rules:

Before proceeding, we have to note that for users to be able to upload an image, they should be authenticated. As this post focuses on uploading an image, we will add a rule that allows an unauthenticated user to upload an image.

Default Firebase Storage permission rules
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if request.auth != null;
}
}
}
Add a new rule and publish

We will add the highlighted rule below, this rule will allow an authenticated or unauthenticated user to read and write the storage with the path reference that starts with/tutorials.

service firebase.storage {
match /b/{bucket}/o {
match /tutorials/{allPaths=**} {
allow read, write;
}

match /{allPaths=**} {
allow read, write: if request.auth != null;
}
}
}

Instead of adding a new rule, we can also remove the authentication rule for all the Storage path references by removing the following condition but this also means that everyone can access your Storage Bucket:

if request.auth != nullservice firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write;
}
}
}

2. Uploading the image in the app

Let’s create a method in our App component to upload the image

In the above method, apart from uploading the image, we are also appending uploaded image URL to other images and persisting them in the AsyncStorage. When you are building an application, you can save the image URLs in a database, for example, a Firebase Cloud Store(Firebase database). We are also getting the upload progress and keep it in the state, which we will use later to design the progress bar.

Bonus

Designing the progress bar

To design the progress bar is easy, in our example we appended a block view and gave it a percentage of progress as width like below:

Append a view block to the image

The add the progress styles:

progressBar: {  backgroundColor: 'rgb(3, 154, 229)',  height: 3,  shadowColor: '#000',}
Progress bar(Sky blue line under the image)

Retrieving the images from the AsyncStorage and rendering them

In our componentDidMount method, we will retrieve images from AsyncStorage and store them in the state as follows:

We’ll later get the image URLs from the state and render them using Flatlist React Native component.

Below is the full code of the App component(App.js), including the styles:

After implementing all of the above, we’ll have the following app view.

Final App View

Also, we’ll see the uploaded images in the Firebase bucket dashboard:

Images in the Storage Bucket

For a better understanding, I used one main component file which includes all the functionalities and styles 🥰.

You can get the full codebase here: https://github.com/muhozi/RnFirebaseImgUpload

That’s it.

Cheers 🎉.

--

--