Easy Way to Insatntly Get the Urls of Taken Photos Reactnative

Cover image for React Native Series: How to save an image from a remote url in React Native

majiyd

majiyd

Posted on • Updated on

React Native Series: How to save an paradigm from a remote url in React Native

In this article, I will evidence you lot how to save an image from a remote url to your device using react-native.

TL/DR Find the full lawmaking in this github repo

I'm assuming you already accept node and react-native set up up, if you don't, delight check out the official docs to acquire how to gear up a react native projection.

The post-obit packages are required for this tutorial

  • @react-native-community/cameraroll
  • rn-fetch-blob

Installing the packages

Install the packages using yarn

            yarn add together @react-native-community/cameraroll rn-fetch-blob                      

Enter fullscreen mode Leave fullscreen mode

or npm

            npm              install              @react-native-customs/cameraroll rn-fetch-blob              --salvage                      

Enter fullscreen mode Exit fullscreen way

Link the native code

if your react-native version >= 0.sixty, autolink using

                          cd              ios              &&              pod              install                      

Enter fullscreen mode Exit fullscreen way

else link manually with

            react-native              link              @react-native-community/cameraroll  react-native              link              rn-fetch-blob                      

Enter fullscreen mode Exit fullscreen way

With this, we are done installing the required packages. Navigate to app.js

            project_dir -> app.js                      

Enter fullscreen style Leave fullscreen mode

delete the default react native code and replace it with this block

                          // app.js              import              React              from              '              react              '              ;              import              {              SafeAreaView              ,              StyleSheet              ,              StatusBar              ,              Text              }              from              '              react-native              '              ;              course              App              extends              React              .              Component              {              render              ()              {              render              (              <>              <              StatusBar              barStyle              =              "              dark-content              "              />              <              SafeAreaView              style              =              {              styles              .              container              }              >              <              Text              >              Save              Prototype              <              /Text              >                            <              /SafeAreaView              >                            <              /              >                            );              }              }              export              default              App              ;              const              styles              =              StyleSheet              .              create              ({              container              :              {              backgroundColor              :              '              #2FF345CC              '              ,              flex              :              1              ,              justifyContent              :              '              middle              '              ,              alignItems              :              '              eye              '              ,              },              });                      

Enter fullscreen manner Exit fullscreen mode

Run the app in the simulator with

            react-native run-ios              # or react-native run-android                      

Enter fullscreen mode Exit fullscreen way

You should see something like this
simple-react-native-app

Setting upward permissions

The user's permission is required for cameraroll to save images to their device. On ios, NSPhotoLibraryUsageDescription and NSPhotoLibraryAddUsageDescription keys must be gear up in info.plist with a cord that describes how your app will use this information. Navigate to info.plist

            project_dir -> ios -> project_name -> info.plist                      

Enter fullscreen fashion Get out fullscreen mode

add the following block to info.plist

                          <!-- info.plist -->              <?xml version="one.0" encoding="UTF-8"?>              <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">              <plist              version=              "1.0"              >              <dict>              ...              <fundamental>NSPhotoLibraryAddUsageDescription</key>              <string>This app would like to salvage images to your device.</string>              <key>NSPhotoLibraryUsageDescription</key>              <string>This app would like to save images to your device.</string>              ...              </dict>              </plist>                      

Enter fullscreen mode Exit fullscreen style

Acquit in mind that the clarification cord must be a chip more than descriptive than this.

On android, permission is required to write to external storage. Permission can be requested past calculation the following block to AndroidManifest.xml

            # navigate to AndroidManifest.xml project_dir -> android -> app -> src -> main -> AndroidManifest.xml                      

Enter fullscreen manner Exit fullscreen mode

                          <!-- AndroidManifest.xml -->              <manifest              xmlns:android=              "http://schemas.android.com/apk/res/android"              package=              "com.saveremoteimage"              >              ...              <uses-permission              android:proper name=              "android.permission.WRITE_EXTERNAL_STORAGE"              />              ...              </manifest>                      

Enter fullscreen manner Exit fullscreen manner

Implementation

This is an image of what the end product would look like

save-remote-image-react-native

Allow's build the UI. Kickoff, start by creating a view that would contain all our components

                          // app.js              ...              import              {              SafeAreaView              ,              StyleSheet              ,              StatusBar              ,              Text              ,              View              }              from              '              react-native              '              ;              class              App              extends              React              .              Component              {              return              ()              {              return              (              <>              <              StatusBar              barStyle              =              "              dark-content              "              />              <              SafeAreaView              style              =              {              styles              .              container              }              >              <              View              fashion              =              {              styles              .              app              }              >              <              Text              >              Save              Paradigm              <              /Text              >                            <              /View              >                            <              /SafeAreaView              >                            <              /              >                            );              }              }              ...              const              styles              =              StyleSheet              .              create              ({              ...              app              :              {              backgroundColor              :              '              #11131B              '              ,              flex              :              ane              ,              alignSelf              :              '              stretch              '              ,              alignItems              :              '              heart              '              ,              paddingVertical              :              xxx              ,              },              });                      

Enter fullscreen mode Leave fullscreen mode

Then we add a TextInput. This TextInput is where the url of the prototype would exist entered

                          // app.js              ...              import              {              ...              TextInput              ,              }              from              '              react-native              '              ;              grade              App              extends              React              .              Component              {              return              ()              {              render              (              <>              ...              <              View              style              =              {              styles              .              app              }              >              <              Text              style              =              {              styles              .              headerText              }              >              React              Native              Image              Downloader              <              /Text              >                            <              View              style              =              {              styles              .              textInputWrapper              }              >              <              TextInput              placeholder              =              "              Enter prototype url hither              "              style              =              {              styles              .              textInput              }              /              >                            <              /View              >                            <              Text              >              Save              Epitome              <              /Text              >                            <              /View              >                            ...              <              /              >                            );              }              }              ...              const              styles              =              StyleSheet              .              create              ({              ...              headerText              :              {              marginTop              :              50              ,              fontSize              :              26              ,              colour              :              '              white              '              ,              },              textInputWrapper              :              {              marginTop              :              30              ,              alignSelf              :              '              stretch              '              ,              padding              :              10              ,              },              textInput              :              {              padding              :              ten              ,              backgroundColor              :              '              #EFEFEF              '              ,              borderWidth              :              1              ,              borderColor              :              '              #DDD              '              ,              borderRadius              :              3              ,              },              });                      

Enter fullscreen fashion Exit fullscreen mode

At this point, your app should look like this
react-native-app-with-text-input

At present, allow's create a view that would contain a preview of the epitome to be downloaded

                          // app.js                            ...              class              App              extends              React              .              Component              {              render              ()              {              return              (              <>              ...              <              View              style              =              {              styles              .              app              }              >              ...              <              View              way              =              {              styles              .              imagePreview              }              /              >                            <              Text              >              Save              Epitome              <              /Text              >                            <              /View              >                            ...              <              /              >                            );              }              }              ...              const              styles              =              StyleSheet              .              create              ({              ...              imagePreview              :              {              height              :              300              ,              width              :              300              ,              backgroundColor              :              '              purple              '              ,              marginTop              :              thirty              ,              },              });                      

Enter fullscreen mode Go out fullscreen style

Finally, let's add together a button nosotros can employ to initiate the download.

                          // app.js              ...              import              {              ...              TouchableOpacity              ,              }              from              '              react-native              '              ;              class              App              extends              React              .              Component              {              render              ()              {              return              (              <>              ...              <              View              style              =              {              styles              .              app              }              >              ...              <              View              style              =              {              styles              .              imagePreview              }              /              >                            <              TouchableOpacity              style              =              {              styles              .              downloadButton              }              >              <              Text              >              Download              Image              <              /Text              >                            <              /TouchableOpacity              >                            <              /View              >                            ...              <              /              >                            );              }              }              ...              const              styles              =              StyleSheet              .              create              ({              ...              downloadButton              :              {              backgroundColor              :              '              white              '              ,              marginTop              :              40              ,              paddingHorizontal              :              40              ,              paddingVertical              :              20              ,              borderRadius              :              iii              ,              },              });                      

Enter fullscreen mode Leave fullscreen mode

At the this point, your app should look similar this
download image from remote url with react native wip

At present nosotros bind the value of the TextInput to state and so information technology is accessible elsewhere.

                          ...              class              App              extends              React              .              Component              {              state              =              {              url              :              ''              ,              };              updateUrl              =              url              =>              {              this              .              setState              ({              url              });              };              render              ()              {              const              {              url              }              =              this              .              state              ;              return              (              <>              <              StatusBar              barStyle              =              "              dark-content              "              />              <              SafeAreaView              style              =              {              styles              .              container              }              >              <              View              style              =              {              styles              .              app              }              >              ...              <              View              style              =              {              styles              .              textInputWrapper              }              >              <              TextInput              placeholder              =              "              Enter image url here              "              style              =              {              styles              .              textInput              }              value              =              {              url              }              onChangeText              =              {              text              =>              this              .              updateUrl              (              text              )}              /              >                            <              /View              >                            ...              <              /SafeAreaView              >                            <              /              >                            );              }              }              export              default              App              ;              ...                      

Enter fullscreen mode Exit fullscreen fashion

Next, we'll bind the url in state to an prototype componenent so it can be displayed.

                          import              React              from              '              react              '              ;              import              {              ...              Prototype              ,              }              from              '              react-native              '              ;              class              App              extends              React              .              Component              {              ...              return              ()              {              ..              return              (              <>              <              StatusBar              barStyle              =              "              dark-content              "              />              <              SafeAreaView              style              =              {              styles              .              container              }              >              <              View              manner              =              {              styles              .              app              }              >              <              Text              style              =              {              styles              .              headerText              }              >              React              Native              Image              Downloader              <              /Text              >                            <              View              mode              =              {              styles              .              textInputWrapper              }              >              ...              <              /View              >                            {              /* nosotros've replaced the View with an Image*/              }              <              Prototype              source              =              {{              uri              :              url              }}              manner              =              {              styles              .              imagePreview              }              /              >                            <              TouchableOpacity              style              =              {              styles              .              downloadButton              }              >              <              Text              >              Download              Epitome              <              /Text              >                            <              /TouchableOpacity              >                            <              /View              >                            <              /SafeAreaView              >                            <              /              >                            );              }              }              ...                      

Enter fullscreen mode Exit fullscreen style

save-remote-image-react-native

Adding download functionality

Allow'southward create a handleDownload part and attach information technology to our TouchableOpacity

                          import              React              from              '              react              '              ;              import              {              ...              }              from              '              react-native              '              ;              import              CameraRoll              from              '              @react-native-customs/cameraroll              '              ;              import              RNFetchBlob              from              '              rn-fetch-blob              '              ;              grade              App              extends              React              .              Component              {              ...              handleDownload              =              async              ()              =>              {              RNFetchBlob              .              config              ({              fileCache              :              true              ,              appendExt              :              '              png              '              ,              })              .              fetch              (              '              GET              '              ,              this              .              state              .              url              )              .              then              (              res              =>              {              CameraRoll              .              saveToCameraRoll              (              res              .              data              ,              '              photo              '              )              .              so              (              res              =>              console              .              log              (              res              ))              .              catch              (              err              =>              console              .              log              (              err              ))              })              .              take hold of              (              mistake              =>              console              .              log              (              error              );              };              return              ()              {              ...              return              (              <>              <              StatusBar              barStyle              =              "              dark-content              "              />              <              SafeAreaView              style              =              {              styles              .              container              }              >              ...              <              TouchableOpacity              style              =              {              styles              .              downloadButton              }              onPress              =              {              this              .              handleDownload              }              >              <              Text              >              Download              Image              <              /Text              >                            <              /TouchableOpacity>                                                        ...              <              /SafeAreaView              >                            <              /              >                            );              }              }              ...                      

Enter fullscreen mode Get out fullscreen fashion

For android devices you need to ensure y'all have permission to relieve images.

                          import              React              from              '              react              '              ;              import              {              ...              PermissionsAndroid              ,              Alert              ,              }              from              '              react-native              '              ;              import              CameraRoll              from              '              @react-native-customs/cameraroll              '              ;              import              RNFetchBlob              from              '              rn-fetch-blob              '              ;              grade              App              extends              React              .              Component              {              ...              getPermissionAndroid              =              async              ()              =>              {              try              {              const              granted              =              await              PermissionsAndroid              .              asking              (              PermissionsAndroid              .              PERMISSIONS              .              WRITE_EXTERNAL_STORAGE              ,              {              title              :              '              Image Download Permission              '              ,              message              :              '              Your permission is required to save images to your device              '              ,              buttonNegative              :              '              Cancel              '              ,              buttonPositive              :              '              OK              '              ,              },              );              if              (              granted              ===              PermissionsAndroid              .              RESULTS              .              GRANTED              )              {              return              truthful              ;              }              Alert              .              alert              (              '              Relieve remote Image              '              ,              '              Grant Me Permission to save Image              '              ,              [{              text              :              '              OK              '              ,              onPress              :              ()              =>              panel              .              log              (              '              OK Pressed              '              )}],              {              cancelable              :              false              },              );              }              catch              (              err              )              {              Alert              .              alert              (              '              Salvage remote Epitome              '              ,              '              Failed to save Image:                            '              +              err              .              message              ,              [{              text              :              '              OK              '              ,              onPress              :              ()              =>              console              .              log              (              '              OK Pressed              '              )}],              {              cancelable              :              fake              },              );              }              };              handleDownload              =              async              ()              =>              {              // if device is android you lot have to ensure yous have permission              if              (              Platform              .              OS              ===              '              android              '              )              {              const              granted              =              await              this              .              getPermissionAndroid              ();              if              (              !              granted              )              {              return              ;              }              }              RNFetchBlob              .              config              ({              fileCache              :              true              ,              appendExt              :              '              png              '              ,              })              .              fetch              (              '              GET              '              ,              this              .              state              .              url              )              .              so              (              res              =>              {              ...              };              render              ()              {              ...              }              }              ...                      

Enter fullscreen mode Go out fullscreen way

Finally lets add an ActivityIndicator and some helpful feedback messages. Your final lawmaking should look like this:

Here'due south a niggling video demo.

leelopead.blogspot.com

Source: https://dev.to/majiyd/react-native-series-how-to-save-an-image-from-a-remote-url-in-react-native-109d

0 Response to "Easy Way to Insatntly Get the Urls of Taken Photos Reactnative"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel