Mhret Aatifa

Mhret Aatifa

1589555340

React Native Share, A Simple Tool for Share Message and File

react-native-share

React Native Share, a simple tool for share message and file to other apps.

Sponsors

If you use this library on your commercial/personal projects, you can help us by funding the work on specific issues that you choose by using IssueHunt.io!

This gives you the power to prioritize our work and support the project contributors. Moreover it’ll guarantee the project will be updated and maintained in the long run.

issuehunt-image

Getting started

If you are using react-native >= 0.60.0 please use react-native-share >= 2.0.0

Automatic Way

yarn add react-native-share

or if you’re using npm

npm install react-native-share --save

Requirements:

  1. Xcode 11 or higher
  2. iOS 13 SDK or higher

Important:

Linking is not needed anymore. react-native@0.60.0+ supports dependencies auto linking. For iOS you also need additional step to install auto linked Pods:

npx pod-install

If you are using react-native <= 0.59.10 please use react-native-share <= 1.2.1:

If you are having any problems with this library, or need to use >= 2.0.0 please refer to: jetifier.

After installing jetifier, runs a npx jetify -r and test if this works by running a react-native run-android.

Automatic Way

yarn add react-native-share
react-native link react-native-share # not needed for react-native >= 0.60.0

or if you’re using npm

npm install react-native-share --save
react-native link react-native-share # not needed for react-native >= 0.60.0

We recommend using the releases from npm, however you can use the master branch if you need any feature that is not available on NPM. By doing this you will be able to use unreleased features, but the module may be less stable. yarn:

yarn add react-native-share@git+https://git@github.com/react-native-community/react-native-share.git

LSApplicationQueriesSchemes on iOS

Remember to add instagram, facebook or whatever queries schemes you need to LSApplicationQueriesSchemes field in your Info.plist. This is required to share content directly to other apps like Instagram, Facebook etc. Values for queries schemes can be found in Social field of RNShare class.

Manual install

iOS Install

  1. yarn add react-native-share

  2. In XCode, in the project navigator, right click LibrariesAdd Files to [your project's name]

  3. Go to node_modulesreact-native-shareios and add RNShare.xcodeproj

  4. In XCode, in the project navigator, select your project. Add libRNShare.a to your project’s Build PhasesLink Binary With Libraries

  5. In XCode, in the project navigator, select your project. Add Social.framework and MessageUI.framework to your project’s GeneralLinked Frameworks and Libraries

  6. In iOS 9 or higher, you should add app list that you will share. If you want to share Whatsapp and Mailto, you should write LSApplicationQueriesSchemes in info.plist

    <key>LSApplicationQueriesSchemes</key>
    <array>
      <string>whatsapp</string>
      <string>mailto</string>
    </array>
    
  7. (Optional) Also following lines allows users to save photos, add them in info.plist

    <key>NSPhotoLibraryAddUsageDescription</key>
    <string>$(PRODUCT_NAME) wants to save photos</string>
    
  8. Run your project (Cmd+R)

iOS Install (using Pods)

If you wish, you can use cocopoads to use react-native-share.

You just need to add to your Podfile the react-native-share dependency.

  # React-Native-Share pod
  pod 'RNShare', :path => '../node_modules/react-native-share'

After that, just run a pod install or pod udpate to get up and running with react-native-share.

Then run a react-native link react-native-share, and doing the steps 6 and 7.

You can also see our example to see how you need to setup your podfile.

Btw, We also recommend reading this amazing article about how pods and rn work together. =D

Android Install

  1. yarn add react-native-share

  2. Open up android/app/src/main/java/[...]/MainApplication.java

    • Add import cl.json.RNSharePackage; and import cl.json.ShareApplication; to the imports at the top of the file
    • Add new RNSharePackage() to the list returned by the getPackages() method
  3. Append the following lines to android/settings.gradle:

    include ':react-native-share'
    project(':react-native-share').projectDir = new File(rootProject.projectDir, 	'../node_modules/react-native-share/android')
    
    
  4. Insert the following lines inside the dependencies block in android/app/build.gradle:

      implementation project(':react-native-share')
    
    
  5. (Optional) Follow this for implementing Provider

Windows Install

Read it! :D

  1. yarn add react-native-share
  2. In Visual Studio add the RNShare.sln in node_modules/react-native-share/windows/RNShare.sln folder to their solution, reference from their app.
  3. Open up your MainPage.cs app
  • Add using Cl.Json.RNShare; to the usings at the top of the file
  • Add new RNSharePackage() to the List<IReactPackage> returned by the Packages method

Methods

open(options)

Open Simple share dialog

Returns a promise that fulfills or rejects as soon as user successfully open the share action sheet or cancelled/failed to do so. As a result you might need to further handle the rejection while necessary. e.g.

*For share multiple files, you must using option urls instead of url to share multiple files/images/docs. Example could be found in Example folder

  Share.open(options)
    .then((res) => { console.log(res) })
    .catch((err) => { err && console.log(err); });

Supported options:

Name Type Description
url string URL you want to share (only support base64 string in iOS & Android).
urls Array[string] array of base64 string you want to share (only support iOS & Android).
type string File mime type (optional)
message string
title string (optional)
subject string (optional)
email string Email of addressee (optional)
excludedActivityTypes string (optional)
failOnCancel boolean (defaults to true) Specifies whether promise should reject if user cancels share dialog (optional)
showAppsToView boolean (optional) only android
filename string only support base64 string in Android
saveToFiles boolean Open only Files app (optional, supports only urls (base64 string or path), requires iOS 11 or later)
filenames Array[string] array of filename for base64 urls array in Android
activityItemSources Array[Object] (optional) Array of activity item sources (iOS only). Each items should conform to ActivityItemSource type. See below.

Url format when sharing a file

Share base 64 file

When share a base 64 file, please follow the format below:

url: "data:<data_type>/<file_extension>;base64,<base64_data>"

Share file directly

When share a local file directly, please follow the format below:

url: "file://<file_path>",

Provide data to share by using activityItemSources (in iOS)

In order to share different data according to activities or to customize the share sheet, you can provide the data by using activityItemSources .

See here for more information about UIActivityItemSource.

Example
import { Platform } from 'react-native';
import Share from 'react-native-share';

const url = 'https://awesome.contents.com/';
const title = 'Awesome Contents';
const message = 'Please check this out.';
const icon = 'data:<data_type>/<file_extension>;base64,<base64_data>';
const options = Platform.select({
  ios: {
    activityItemSources: [
      { // For sharing url with custom title.
        placeholderItem: { type: 'url', content: url },
        item: {
          default: { type: 'url', content: url },
        },
        subject: {
          default: title,
        },
        linkMetadata: { originalUrl: url, url, title },
      },
      { // For sharing text.
        placeholderItem: { type: 'text', content: message },
        item: {
          default: { type: 'text', content: message },
          message: null, // Specify no text to share via Messages app.
        },
        linkMetadata: { // For showing app icon on share preview.
           title: message
        },
      },
      { // For using custom icon instead of default text icon at share preview when sharing with message.
        placeholderItem: {
          type: 'url',
          content: icon
        },
        item: {
          default: {
            type: 'text',
            content: `${message} ${url}`
          },
        },
        linkMetadata: {
           title: message,
           icon: icon
        }
      },
    ],
  },
  default: {
    title,
    subject: title,
    message: `${message} ${url}`,
  },
});

Share.open(options);
ActivityItemSource
Name Type Description
placeholderItem Object An object to use as a placeholder for the actual data. This should comform to ActivityItem type.
item Object An object that contains the final data object to be acted on for each activity types. This should be { [ActivityType]: ?ActivityItem } .
subject Object (optional) An object that contains a string to use as the contents of the subject field for each activity types. This should be { [ActivityType]: string } .
dataTypeIdentifier Object (optional) An object that contains the UTI for the item for each activity types. This should be { [ActivityType]: string } . See here for more information.
thumbnailImage Object (optional) An object that contains the URL to the image to use as a preview for the item for each activity types. This should be { [ActivityType]: string } . The URL should begin with data: and contain the data as base 64 encoded string.
linkMetadata Object (optional) An object that contains the metadata about a URL, including its title, icon, images, and video. See LinkMetadata.
ActivityType
  • addToReadingList
  • airDrop
  • assignToContact
  • copyToPasteBoard
  • mail
  • message
  • openInIBooks (iOS 9+)
  • postToFacebook
  • postToFlickr
  • postToTencentWeibo
  • postToTwitter
  • postToVimeo
  • postToWeibo
  • print
  • saveToCameraRoll
  • markupAsPDF (iOS 11+)

Also you can use default in order to specify default behavior.

ActivityItem
Name Type Description
type text url
content string Text or URL to share. You can specify image with URL that begins with data and contains the data as base 64 encoded string.
LinkMetadata
Name Type Description
originalUrl string (optional) The original URL of the metadata request.
url string (optional) The URL that returns the metadata, taking server-side redirects into account.
title string (optional) A representative title for the URL.
icon string (optional) A URL of the file corresponding to a representative icon for the URL.
image string (optional) A URL of the file corresponding to a representative image for the URL.
remoteVideoUrl string (optional) A remote URL corresponding to a representative video for the URL.
video string (optional) A URL of the file corresponding to a representative video for the URL.

shareSingle(options) (in iOS & Android)

Open share dialog with specific application

This returns a promise too.

Supported options:

Name Type Description
url string URL you want to share
type string File mime type (optional)
message string
title string (optional)
subject string (optional)
email string Email of addressee (optional)
social string supported social apps: List
forceDialog boolean (optional) only android. Avoid showing dialog with buttons Just Once / Always. Useful for Instagram to always ask user if share as Story or Feed

NOTE: If both message and url are provided, url will be concatenated to the end of message to form the body of the message. If only one is provided it will be used

isPackageInstalled() (in Android)

It’s a method that checks if an app (package) is installed on Android. It returns a promise with isInstalled. e.g.

Checking if Instagram is installed on Android.

Share.isPackageInstalled('com.instagram.android')
  .then(({ isInstalled }) => console.log(isInstalled))

NOTE: in iOS you can use Linking.canOpenURL(url)

Static Values for social

These can be assessed using Share.Social property For eg.

import Share from 'react-native-share';

const shareOptions = {
    title: 'Share via',
    message: 'some message',
    url: 'some share url',
    social: Share.Social.WHATSAPP,
    whatsAppNumber: "9199999999",  // country code + phone number
    filename: 'test' , // only for base64 file in Android
};
Share.shareSingle(shareOptions);
Name Android iOS Windows
FACEBOOK yes yes no
FACEBOOK_STORIES no yes no
PAGESMANAGER yes no no
WHATSAPP yes yes no
INSTAGRAM yes yes no
INSTAGRAM_STORIES no yes no
GOOGLEPLUS yes yes no
EMAIL yes yes no
PINTEREST yes no no
SMS yes no no
SNAPCHAT yes no no
MESSENGER yes no no
LINKEDIN yes no no

How it looks:

Android IOS Windows
Simple Share Demo Android Demo iOS Demo Windows
UI Component Demo Android UI Component Demo Android UI Component TODO

Troubleshooting

Language Support (iOS)

On iOS, share component reads language value from CFBundleDevelopmentRegion at Info.plist file. By changing CFBundleDevelopmentRegion value you can change default language for component.

<key>CFBundleDevelopmentRegion</key>
<string>en</string>

For supporting multi language, you can add CFBundleAllowMixedLocalizations key to Info.plist.

<key>CFBundleAllowMixedLocalizations</key>
<string>true</string>

LinkPresentation.h file not found

  1. Check iOS SDK version running this command: xcodebuild -showsdks
  2. If your SDK is 12 or lower you need to update to Xcode 11 with iOS SDK 13
  3. Build the app with Xcode 11 and everything works ok

Share Remote PDF File with Gmail & WhatsApp (iOS)

When sharing a pdf file with base64, there are two current problems.

  1. On WhatsApp base64 wont be recognized => nothing to share
  2. In the GmailApp the file extension is wrong (.dat).

Therefore we use this “workaround” in order to handle pdf sharing for iOS Apps to mentioned Apps

  1. Install react-native-fetch-blob
  2. Set a specific path in the RNFetchBlob configurations
  3. Download the PDF file to temp device storage
  4. Share the response’s path() of the donwloaded file directly

Code:

static sharePDFWithIOS(fileUrl, type) {
  let filePath = null;
  let file_url_length = fileUrl.length;
  const configOptions = {
    fileCache: true,
    path:
      DIRS.DocumentDir + (type === 'application/pdf' ? '/SomeFileName.pdf' : '/SomeFileName.png') // no difference when using jpeg / jpg / png /
  };
  RNFetchBlob.config(configOptions)
    .fetch('GET', fileUrl)
    .then(async resp => {
      filePath = resp.path();
      let options = {
        type: type,
        url: filePath // (Platform.OS === 'android' ? 'file://' + filePath)
      };
      await Share.open(options);
      // remove the image or pdf from device's storage
      await RNFS.unlink(filePath);
    });
}

Nothing to do on Android. You can share the pdf file with base64

static sharePDFWithAndroid(fileUrl, type) {
  let filePath = null;
  let file_url_length = fileUrl.length;
  const configOptions = { fileCache: true };
  RNFetchBlob.config(configOptions)
    .fetch('GET', fileUrl)
    .then(resp => {
      filePath = resp.path();
      return resp.readFile('base64');
    })
    .then(async base64Data => {
      base64Data = `data:${type};base64,` + base64Data;
      await Share.open({ url: base64Data });
      // remove the image or pdf from device's storage
      await RNFS.unlink(filePath);
    });
}

Static Values for Instagram Stories

These can be assessed using Share.Social property For eg.

import Share from 'react-native-share';

const shareOptions = {
    method: Share.InstagramStories.SHARE_BACKGROUND_AND_STICKER_IMAGE,
    backgroundImage: 'http://urlto.png',
    stickerImage: 'data:image/png;base64,<imageInBase64>', //or you can use "data:" link
    backgroundBottomColor: '#fefefe',
    backgroundTopColor: '#906df4',
    attributionURL: 'http://deep-link-to-app', //in beta
    social: Share.Social.INSTAGRAM_STORIES
};
Share.shareSingle(shareOptions);

Supported options for INSTAGRAM_STORIES:

Name Type Description
backgroundImage string URL you want to share
stickerImage string URL you want to share
method string List
backgroundBottomColor string (optional) default #837DF4
backgroundTopColor string (optional) default #906df4
attributionURL string (optional) facebook beta-test

Instagram stories method list

Name Required options
SHARE_BACKGROUND_IMAGE backgroundImage
SHARE_STICKER_IMAGE stickerImage
SHARE_BACKGROUND_AND_STICKER_IMAGE backgroundImage, stickerImage

Static Values for Facebook Stories

These can be assessed using Share.Social property For eg.

import Share from 'react-native-share';

const shareOptions = {
    method: Share.FacebookStories.SHARE_BACKGROUND_AND_STICKER_IMAGE,
    backgroundImage: 'http://urlto.png', // url or an base64 string
    stickerImage: 'data:image/png;base64,<imageInBase64>', //or you can use "data:" url
    backgroundBottomColor: '#fefefe',
    backgroundTopColor: '#906df4',
    attributionURL: 'http://deep-link-to-app', //in beta
    appId: '219376304', //facebook appId
    social: Share.Social.FACEBOOK_STORIES
};
Share.shareSingle(shareOptions);

Supported options for FACEBOOK_STORIES:

Name Type Description
appId string (required) facebook appId
backgroundImage string URL you want to share
stickerImage string URL you want to share
method string List
backgroundBottomColor string (optional) default #837DF4
backgroundTopColor string (optional) default #906df4
attributionURL string (optional) facebook beta-test

Facebook stories method list

Name Required options
SHARE_BACKGROUND_IMAGE backgroundImage
SHARE_STICKER_IMAGE stickerImage
SHARE_BACKGROUND_AND_STICKER_IMAGE backgroundImage, stickerImage

Adding your implementation of FileProvider

Android guide.

  • applicationId should be defined in the defaultConfig section in your android/app/build.gradle:

  • File: android/app/build.gradle

    defaultConfig {
        applicationId "com.yourcompany.yourappname"
        ...
    }
    
    
  • Add this <provider> section to your AndroidManifest.xml

    File: AndroidManifest.xml

    <application>
        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:grantUriPermissions="true"
            android:exported="false">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/filepaths" />
        </provider>
    </application>
    
  • Create a filepaths.xml under this directory: android/app/src/main/res/xml.

    In this file, add the following contents:

    File: android/app/src/main/res/xml/filepaths.xml

    <?xml version="1.0" encoding="utf-8"?>
    <paths xmlns:android="http://schemas.android.com/apk/res/android">
      <external-path name="myexternalimages" path="Download/" />
    </paths>
    
  • Edit your MainApplication.java class to add implements ShareApplication and getFileProviderAuthority

  • The getFileProviderAuthority function returns the android:authorities value added in the AndroidManifest.xml file

  • applicationId is defined in the defaultConfig section of your android/app/build.gradle and referenced using BuildConfig.APPLICATION_ID

    import cl.json.ShareApplication
    public class MainApplication extends Application implements ShareApplication, ReactApplication {
    
         @Override
         public String getFileProviderAuthority() {
                return BuildConfig.APPLICATION_ID + ".provider";
         }
    
         // ...Your own code
    
    }
    

Mocking with Jest

  • To mock when using Jest. Add the below line on your __mock__ directory.
jest.mock('react-native-share', () => ({
  default: jest.fn(),
}));

Download Details:

Author: react-native-community

GitHub: https://github.com/react-native-community/react-native-share

#react-native #reactjs #programming

What is GEEK

Buddha Community

React Native Share, A Simple Tool for Share Message and File
Autumn  Blick

Autumn Blick

1598839687

How native is React Native? | React Native vs Native App Development

If you are undertaking a mobile app development for your start-up or enterprise, you are likely wondering whether to use React Native. As a popular development framework, React Native helps you to develop near-native mobile apps. However, you are probably also wondering how close you can get to a native app by using React Native. How native is React Native?

In the article, we discuss the similarities between native mobile development and development using React Native. We also touch upon where they differ and how to bridge the gaps. Read on.

A brief introduction to React Native

Let’s briefly set the context first. We will briefly touch upon what React Native is and how it differs from earlier hybrid frameworks.

React Native is a popular JavaScript framework that Facebook has created. You can use this open-source framework to code natively rendering Android and iOS mobile apps. You can use it to develop web apps too.

Facebook has developed React Native based on React, its JavaScript library. The first release of React Native came in March 2015. At the time of writing this article, the latest stable release of React Native is 0.62.0, and it was released in March 2020.

Although relatively new, React Native has acquired a high degree of popularity. The “Stack Overflow Developer Survey 2019” report identifies it as the 8th most loved framework. Facebook, Walmart, and Bloomberg are some of the top companies that use React Native.

The popularity of React Native comes from its advantages. Some of its advantages are as follows:

  • Performance: It delivers optimal performance.
  • Cross-platform development: You can develop both Android and iOS apps with it. The reuse of code expedites development and reduces costs.
  • UI design: React Native enables you to design simple and responsive UI for your mobile app.
  • 3rd party plugins: This framework supports 3rd party plugins.
  • Developer community: A vibrant community of developers support React Native.

Why React Native is fundamentally different from earlier hybrid frameworks

Are you wondering whether React Native is just another of those hybrid frameworks like Ionic or Cordova? It’s not! React Native is fundamentally different from these earlier hybrid frameworks.

React Native is very close to native. Consider the following aspects as described on the React Native website:

  • Access to many native platforms features: The primitives of React Native render to native platform UI. This means that your React Native app will use many native platform APIs as native apps would do.
  • Near-native user experience: React Native provides several native components, and these are platform agnostic.
  • The ease of accessing native APIs: React Native uses a declarative UI paradigm. This enables React Native to interact easily with native platform APIs since React Native wraps existing native code.

Due to these factors, React Native offers many more advantages compared to those earlier hybrid frameworks. We now review them.

#android app #frontend #ios app #mobile app development #benefits of react native #is react native good for mobile app development #native vs #pros and cons of react native #react mobile development #react native development #react native experience #react native framework #react native ios vs android #react native pros and cons #react native vs android #react native vs native #react native vs native performance #react vs native #why react native #why use react native

Hire Dedicated React Native Developer

Have you ever thought of having your own app that runs smoothly over multiple platforms?

React Native is an open-source cross-platform mobile application framework which is a great option to create mobile apps for both Android and iOS. Hire Dedicated React Native Developer from top React Native development company, HourlyDeveloper.io to design a spectacular React Native application for your business.

Consult with experts:- https://bit.ly/2A8L4vz

#hire dedicated react native developer #react native development company #react native development services #react native development #react native developer #react native

Juned Ghanchi

1621573085

React Native App Developers India, React Native App Development Company

Expand your user base by using react-native apps developed by our expert team for various platforms like Android, Android TV, iOS, macOS, tvOS, the Web, Windows, and UWP.

We help businesses to scale up the process and achieve greater performance by providing the best react native app development services. Our skilled and experienced team’s apps have delivered all the expected results for our clients across the world.

To achieve growth for your business, hire react native app developers in India. You can count on us for all the technical services and support.

#react native app development company india #react native app developers india #hire react native developers india #react native app development company #react native app developers #hire react native developers

Hire Dedicated React Native Developers - WebClues Infotech

Being one of the emerging frameworks for app development the need to develop react native apps has increased over the years.

Looking for a react native developer?

Worry not! WebClues infotech offers services to Hire React Native Developers for your app development needs. We at WebClues Infotech offer a wide range of Web & Mobile App Development services based o your business or Startup requirement for Android and iOS apps.

WebClues Infotech also has a flexible method of cost calculation for hiring react native developers such as Hourly, Weekly, or Project Basis.

Want to get your app idea into reality with a react native framework?

Get in touch with us.

Hire React Native Developer Now: https://www.webcluesinfotech.com/hire-react-native-app-developer/

For inquiry: https://www.webcluesinfotech.com/contact-us/

Email: sales@webcluesinfotech.com

#hire react native developers #hire dedicated react native developers #hire react native developer #hiring a react native developer #hire freelance react native developers #hire react native developers in 1 hour

Factors affecting the cost of hiring a React Native developer in USA - TopDevelopers.co

Want to develop app using React Native? Here are the tips that will help to reduce the cost of react native app development for you.
Cost is a major factor in helping entrepreneurs take decisions about investing in developing an app and the decision to hire react native app developers in USA can prove to be fruitful in the long run. Using react native for app development ensures a wide range of benefits to your business. Understanding your business and working on the aspects to strengthen business processes through a cost-efficient mobile app will be the key to success.

#best react native development companies from the us #top react native app development companies in usa #cost of hiring a react native developer in usa #top-notch react native developer in usa #best react native developers usa #react native