Can You Upload a Uri in Firebase
Mega Package Auction is ON! Get ALL of our React Native codebases at 80% OFF disbelieve 🔥
Using React Native you tin can build a variety of app screens that are cantankerous-platform using JavaScript as the main programming linguistic communication. I such app screen feature is uploading photos which is quite a common feature in social media apps. Uploading photos to Firebase Storage is a common practise in React Native apps that have backend integration with Firebase, such equally our React Native templates.
In this tutorial, let'south build a demo app in which you lot are going to create a simple screen that allows yous to pick an prototype from the app running on the device, using an epitome picker and upload information technology to the Firebase Cloud Storage. The second screen is going to display these images.
Getting started
Start by creating a new react native project. Run the following command from a terminal window. After the projection directory is created, navigate inside information technology and install the required dependencies.
npx react-native init uploadStorageDemo cd uploadStorageDemo yarn add react-native-progress react-native-image-picker
Do annotation that this tutorial uses a react-native version above 0.sixty.x. If yous are using a version below that, make sure to seek guidance on how to link native binaries for the libraries mentioned in this tutorial. To follow instructions on how to configure react-native-image-picker for each mobile platform, I highly recommend you lot to go through the official docshere. For iOS, make sure to install pods.
cd ios/ && pod install # after pods install cd ..
Create an upload screen
The current demo app is going to contain 1 screen that will aid the user to select an image from the device's photo library. Create a file chosen UploadScreen.js inside src/screens/ directory and the post-obit mock snippet for now.
import * every bit React from 'react'; import { Text, View } from 'react-native'; export default part UploadScreen() { render ( <View fashion={{ flex: 1, justifyContent: 'eye', alignItems: 'center' }}> <Text>Upload!</Text> </View> ); } Open up App.js file and import the AppTabs.
import React from 'react'; import { StatusBar } from 'react-native'; import UploadScreen from './src/screens/UploadScreen'; const App = () => { return ( <> <StatusBar barStyle="dark-content" /> <UploadScreen /> </> ); }; consign default App; Now, go dorsum to the concluding window and build the react native app for the platform or the OS you lot wish to run it on.
# for iOS npx react-native run-ios # for Android npx react-native run-android
I am going to use the iOS simulator for this demo. Open the app to the simulator and you are going to encounter the following output.
Create a new Firebase Project
To admission the Firebase credentials for each mobile Bone platform and configure them to use the Firebase SDK, create a new Firebase project from theFirebase console, or if you lot already have access to a projection in your panel, you lot tin skip this step. Create a new projection as shown below.
Add the details of your Firebase projection.
Click the button "Create project", and you should be redirected to the dashboard screen. You should meet your newly-created projection on that dashboard.
Add Firebase SDK to React Native app
Using react-native-firebase version v or below, since it was a monorepo, all Firebase dependencies were available from a unmarried module to use in a React Native app. However, with version 6 you have to install dependencies based on Firebase features that you want to use. For example, in the current app, to use storage, y'all are going to install the cadre app package as well equally storage package. Equally said that the core module @react-native-firebase/app is always required. Open a terminal window to install these dependencies.
yarn add @react-native-firebase/app @react-native-firebase/storage
Add together Firebase credentials to your iOS app
Firebase provides a GoogleService-Info.plist file that contains all the API keys as well equally other credentials needed for iOS devices to authenticate the correct Firebase project. To access these credentials, go to back to the "Firebase console", and from the dashboard screen of your Firebase project, open "Project settings" from the side card.
Go to the "Your apps" section and click on the icon iOS to select the platform.
Enter the awarding details and click on the "Register app". Then download the GoogleService-Info.plist file, every bit shown below.
Open Xcode, and so open up the /ios/uploadStorageDemo.xcodeproj file. Right-click on the project proper name and cull the Add Files option—then select the advisable file to add to this project.
Next, open ios/uploadStorageDemo/AppDelegate.m and add together the following header.
#import <Firebase.h>
Within the didFinishLaunchingWithOptions method, add the following configure method.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { if ([FIRApp defaultApp] == null) { [FIRApp configure]; } Go dorsum to the last window to install pods.
cd ios/ && pod install # after pods are installed cd ..
Make certain you build the iOS app before running it. Open up
npx react-native run-ios
Add Firebase credentials to your Android app
For Android apps, Firebase provides a google-services.json file that contains all the API keys as well equally other credentials needed for Android devices to authenticate the correct Firebase projection. Go to the "Your apps" section and click on the icon Android to select the platform.
Download the google-services.json file.
Now copy the downloaded JSON file in React Native projection at the following location: /android/app/google-services.json. Open up your android/build.gradle file to add together the post-obit snippet.
dependencies { // ... classpath 'com.google.gms:google-services:4.2.0' } Adjacent, open android/app/build.gradle file, and at the very lesser of this file, add together the post-obit snippet.
apply plugin: 'com.google.gms.google-services'
Lastly, make sure y'all build the Android app.
npx react-native run-android
Using React Native Image Picker
In this section, let us showtime building the app. Start by opening the file UploadScreen.js and import the following statements.
import React, { useState } from 'react'; import { View, SafeAreaView, Text, TouchableOpacity, StyleSheet, Platform, Alarm, Epitome } from 'react-native'; import ImagePicker from 'react-native-image-picker'; import storage from '@react-native-firebase/storage'; import * as Progress from 'react-native-progress'; Inside the office component UploadScreen create three state variables. The start, epitome is going to exist used to store the URI of the source of the image. The same URI volition be then used to display the image picked by the user and to upload the paradigm to the Firebase deject storage. The second country variable is uploading that is going to be false default. This is going to keep track of whether the image is uploading to the cloud storage or not. The third variable transferred is going to track the progress of the epitome being upload.
export default function UploadScreen() { const [image, setImage] = useState(zero); const [uploading, setUploading] = useState(false); const [transferred, setTransferred] = useState(0); //... } Add a helper method called selectImage that is going to utilise the react-native-image-picker to select an epitome from the device'due south library and display the image picker itself. Also, define an options object to prepare backdrop like maximum width and acme as well as a default path. This options object is going to exist passed equally the start parameter in ImagePicker.showPicker() method that is going to return a callback which sends the response object. Using this callback, the path of the image land variable tin can exist gear up. Yous can find the complete set of options to laissez passer in the official docshere.
const selectImage = () => { const options = { maxWidth: 2000, maxHeight: 2000, storageOptions: { skipBackup: truthful, path: 'images' } }; ImagePicker.showImagePicker(options, response => { if (response.didCancel) { panel.log('User cancelled epitome picker'); } else if (response.error) { panel.log('ImagePicker Fault: ', response.error); } else if (response.customButton) { console.log('User tapped custom push button: ', response.customButton); } else { const source = { uri: response.uri }; console.log(source); setImage(source); } }); }; Define another helper method called uploadImage that is going to upload the image to the cloud storage. This method is going to be asynchronous past default and then let us async-await syntax. Also, when this method triggers, update the value of uploading to truthful and transferred to 0 to track the progress of the image beingness upload to the storage. Using storage from Firebase yous can trigger the paradigm upload. It is important to note that the filename has to be passed every bit a reference likewise as the image URI using putFile in the order described below. After the image has uploaded to the storage, display an alarm method using react native component Alert and set state variables to default equally shown below.
const uploadImage = async () => { const { uri } = image; const filename = uri.substring(uri.lastIndexOf('/') + 1); const uploadUri = Platform.OS === 'ios' ? uri.replace('file://', '') : uri; setUploading(true); setTransferred(0); const task = storage() .ref(filename) .putFile(uploadUri); // set progress land task.on('state_changed', snapshot => { setTransferred( Math.circular(snapshot.bytesTransferred / snapshot.totalBytes) * 10000 ); }); try { look task; } catch (due east) { panel.error(eastward); } setUploading(fake); Alert.alert( 'Photo uploaded!', 'Your photo has been uploaded to Firebase Cloud Storage!' ); setImage(cypher); }; Here is the complete JSX returned from this functional component. The progress that you are going to show in the app is going to be in the form of a bar.
export default function UploadScreen() { //... residual of the lawmaking render ( <SafeAreaView style={styles.container}> <TouchableOpacity mode={styles.selectButton} onPress={selectImage}> <Text way={styles.buttonText}>Choice an image</Text> </TouchableOpacity> <View manner={styles.imageContainer}> {image !== zero ? ( <Paradigm source={{ uri: epitome.uri }} manner={styles.imageBox} /> ) : null} {uploading ? ( <View way={styles.progressBarContainer}> <Progress.Bar progress={transferred} width={300} /> </View> ) : ( <TouchableOpacity style={styles.uploadButton} onPress={uploadImage}> <Text style={styles.buttonText}>Upload image</Text> </TouchableOpacity> )} </View> </SafeAreaView> ); } Here are the complete styles for the above component.
const styles = StyleSheet.create({ container: { flex: i, alignItems: 'centre', backgroundColor: '#bbded6' }, selectButton: { borderRadius: 5, width: 150, height: 50, backgroundColor: '#8ac6d1', alignItems: 'center', justifyContent: 'center' }, uploadButton: { borderRadius: 5, width: 150, meridian: 50, backgroundColor: '#ffb6b9', alignItems: 'center', justifyContent: 'center', marginTop: 20 }, buttonText: { color: 'white', fontSize: 18, fontWeight: 'bold' }, imageContainer: { marginTop: 30, marginBottom: 50, alignItems: 'center' }, progressBarContainer: { marginTop: 20 }, imageBox: { width: 300, height: 300 } }); Here is the output you lot are going to get.
To verify that the image is stored in the cloud storage, go dorsum to the Firebase console dashboard and go to the storage section.
Conclusion
Thank you for following upward this tutorial. Using react-native-firebase version 6 brings benefits similar less configuration and focus more on developing the app. Do refer thedocsof react-native-progress for more than data on customizing the progress bar. You can also check this interesting website on cloud storage reviews.
Next Steps
Now that you take learned about resources to learn React Native evolution, here are some other topics you can await into
- Firebase — Push notifications|Firebase storage
- How To in React Native —WebView| Slope| Camera| Adding GIF| Google Maps | Redux | Debugging | Hooks| Nighttime fashion | Deep-link | GraphQL | AsyncStorage | Offline |Nautical chart | Walkthrough | Geolocation | Tinder swipe | App icon | Remainder API
- Payments —Apple Pay|Stripe
- Authentication —Google Login|Facebook login|Phone Auth|
- All-time Resources –App idea|Podcast |Newsletter|App template
If you need a base of operations to start your next React Native app, y'all tin make your side by side crawly app usingmanyReact Native template.
Source: https://instamobile.io/mobile-development/react-native-firebase-storage/
0 Response to "Can You Upload a Uri in Firebase"
Postar um comentário