• This repository has been archived on 09/Mar/2024
  • Stars
    star
    905
  • Rank 50,477 (Top 1.0 %)
  • Language
    C#
  • License
    MIT License
  • Created over 7 years ago
  • Updated 8 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A Unity plugin to natively share files (images, videos, documents, etc.) and/or plain text on Android & iOS

Unity Native Share Plugin

NOTICE: This asset is no longer maintained! Consider using alternative sharing solutions that are actively being maintained. While using this package, expect issues when sharing a file/image/video with a text (see FAQ).

Available on Asset Store: https://assetstore.unity.com/packages/tools/integration/native-share-for-android-ios-112731

Forum Thread: https://forum.unity.com/threads/native-share-for-android-ios-open-source.519865/

Discord: https://discord.gg/UJJt549AaV

Support the Developer โ˜•

This plugin helps you natively share files (images, videos, documents, etc.) and/or plain text on Android & iOS. A ContentProvider is used to share the media on Android.

INSTALLATION

There are 5 ways to install this plugin:

  • import NativeShare.unitypackage via Assets-Import Package
  • clone/download this repository and move the Plugins folder to your Unity project's Assets folder
  • import it from Asset Store
  • (via Package Manager) add the following line to Packages/manifest.json:
    • "com.yasirkula.nativeshare": "https://github.com/yasirkula/UnityNativeShare.git",
  • (via OpenUPM) after installing openupm-cli, run the following command:
    • openupm add com.yasirkula.nativeshare

Android Setup

NativeShare no longer requires any manual setup on Android. If you were using an older version of the plugin, you need to remove NativeShare's <provider ... /> from your AndroidManifest.xml.

For reference, the legacy documentation is available at: https://github.com/yasirkula/UnityNativeShare/wiki/Manual-Setup-for-Android

iOS Setup

There are two ways to set up the plugin on iOS:

HOW TO

Simply create a new NativeShare object and customize it by chaining the following functions as you like (see example code):

  • Clear(): clears the previously set share content (if any). Only useful if the same NativeShare instance will be reused for memory efficiency
  • SetSubject( string subject ): sets the subject (primarily used in e-mail applications)
  • SetText( string text ): sets the shared text. Note that the Facebook app will omit text, if exists (see this topic)
  • SetUrl( string url ): sets the shared url. On supported iOS apps, this url is used to generate a preview of the target webpage. Other iOS apps may append the url to the text or omit it. While sharing a file on iOS or while sharing anything on Android, the url is appended to the text (unless the text already contains the url)
  • AddFile( string filePath, string mime = null ): adds the file at path to the share action. You can add multiple files of different types. The MIME of the file is automatically determined if left null; however, if the file doesn't have an extension and/or you already know the MIME of the file, you can enter the MIME manually. MIME has no effect on iOS
  • AddFile( Texture2D texture, string createdFileName = "Image.png" ): saves the texture to Application.temporaryCachePath with the specified filename and adds the image file to the share action
  • AddEmailRecipient( string emailAddress ): auto-populates the recipients field of e-mail applications on Android platform. Has no effect on iOS
  • SetTitle( string title ): sets the title of the share dialog on Android platform. Has no effect on iOS
  • AddTarget( string androidPackageName, string androidClassName = null ): shares content on a specific application on Android platform. If androidClassName is left null, list of activities in the share dialog will be narrowed down to the activities in the specified androidPackageName that can handle this share action. Note that androidClassName, if provided, must be the full name of the activity (with its package). You can call this function multiple times. This function has no effect on iOS
  • SetCallback( ShareResultCallback callback ): invokes the callback function after the share action is completed. ShareResultCallback has the following signature: void ShareResultCallback( ShareResult result, string shareTarget )
    • ShareResult result can take 3 values:
      • Unknown: we can't determine whether or not the user has shared the content
      • Shared: user has probably shared the content. This value guarantees that the user has at least selected an app from the share sheet. But it is impossible to say whether the user has actually shared the content or cancelled the operation right after selecting the app from the share sheet
      • NotShared: either the user has closed the share sheet immediately or selected an app from the share sheet but then decided not to share the content (unfortunately, most apps return Shared for the latter case)
    • string shareTarget stores information about the app that the user has selected from the share sheet. It can be null or empty, if this information isn't provided. Usually, this is the package name/class name of the selected application. You can use this value to e.g. determine if the user has picked Twitter from the share sheet: shareTarget != null && shareTarget.ToLowerInvariant().Contains( "twitter" )

Finally, calling the Share() function of the NativeShare object will present the share sheet.

UTILITY FUNCTIONS

  • bool NativeShare.TargetExists( string androidPackageName, string androidClassName = null ): returns whether the application with the specified package/class name exists on the Android device. If androidClassName is left null, only the package name is queried. This function always returns true on iOS
  • bool FindTarget( out string androidPackageName, out string androidClassName, string packageNameRegex, string classNameRegex = null ): finds the package/class name of an installed application on the Android device using regular expressions. Returns true if a matching package/class name is found successfully. Can be useful when you want to use the AddTarget function but don't know the exact package/class name of the target activity. If classNameRegex is left null, the first activity in the matching package is returned. This function always returns false on iOS

FAQ

  • Can I share on a specific app?

On Android, you can share on a specific app via AddTarget. For iOS, you can check out this post and see if it works for you: https://forum.unity.com/threads/native-share-for-android-ios-open-source.519865/page-4#post-4011874

  • I can't share image with text on X app

It is just not possible to share an image/file with text/subject on some apps (e.g. Facebook), they intentionally omit either the image or the text from the shared content. These apps require you to use their own SDKs for complex share actions. For best compatibility, I'd recommend you to share either only image or only text.

  • I can't build the project to Android, it says "Android resource linking failed: unexpected element <queries> found in <manifest>" in the error message

NativeShare adds <queries> element to AndroidManifest.xml due to the new package visibility change. The build error can be fixed by following these steps: https://developers.google.com/ar/develop/unity/android-11-build (in my tests, changing "Gradle installed with Unity" wasn't necessary). In the worst case, if you are OK with NativeShare not working on some of the affected devices, then you can open NativeShare.aar with WinRAR or 7-Zip and then remove the <queries>...</queries> element from AndroidManifest.xml.

  • When using Unity as a Library on Android, the app crashes when sharing a file

If you're running the Unity activity in a separate process, then modify AndroidManifest.xml inside NativeShare.aar so that both NativeShareCustomShareDialogActivity and NativeShareBroadcastListener also run on the same process, e.g:

<activity android:name=".NativeShareCustomShareDialogActivity" ... android:process=":YourProcess" />
<receiver android:name=".NativeShareBroadcastListener" ... android:process=":YourProcess" />
  • Can't share, it says "java.lang.ClassNotFoundException: com.yasirkula.unity.NativeShare" in Logcat

If you are sure that your plugin is up-to-date, then enable Custom Proguard File option from Player Settings and add the following line to that file: -keep class com.yasirkula.unity.* { *; }

  • Can't share when using Beebyte Obfuscator, it says "Exception: No such proxy method: xyz.HasManagedCallback()" in Logcat

Add NativeShareNamespace.NSShareResultCallbackAndroid to the Skip Classes section of your obfuscator settings asset.

EXAMPLE CODE

The following code captures the screenshot of the game whenever you tap the screen, saves it in a temporary path and then shares it:

void Update()
{
	if( Input.GetMouseButtonDown( 0 ) )
		StartCoroutine( TakeScreenshotAndShare() );
}

private IEnumerator TakeScreenshotAndShare()
{
	yield return new WaitForEndOfFrame();

	Texture2D ss = new Texture2D( Screen.width, Screen.height, TextureFormat.RGB24, false );
	ss.ReadPixels( new Rect( 0, 0, Screen.width, Screen.height ), 0, 0 );
	ss.Apply();

	string filePath = Path.Combine( Application.temporaryCachePath, "shared img.png" );
	File.WriteAllBytes( filePath, ss.EncodeToPNG() );

	// To avoid memory leaks
	Destroy( ss );

	new NativeShare().AddFile( filePath )
		.SetSubject( "Subject goes here" ).SetText( "Hello world!" ).SetUrl( "https://github.com/yasirkula/UnityNativeShare" )
		.SetCallback( ( result, shareTarget ) => Debug.Log( "Share result: " + result + ", selected app: " + shareTarget ) )
		.Share();

	// Share on WhatsApp only, if installed (Android only)
	//if( NativeShare.TargetExists( "com.whatsapp" ) )
	//	new NativeShare().AddFile( filePath ).AddTarget( "com.whatsapp" ).Share();
}

KNOWN LIMITATIONS

  • Gif files are shared as static images on iOS (to learn more, please see this issue: #22)

More Repositories

1

UnityIngameDebugConsole

A uGUI based console to see debug messages and execute commands during gameplay in Unity
C#
2,117
star
2

UnityAssetUsageDetector

Find usages of the selected asset(s) and/or Object(s) in your Unity project, i.e. list the objects that refer to them
C#
1,693
star
3

UnityRuntimeInspector

Runtime Inspector and Hierarchy solution for Unity for debugging and runtime editing purposes
C#
1,676
star
4

UnityNativeGallery

A native Unity plugin to interact with Gallery/Photos on Android & iOS (save and/or load images/videos)
Objective-C++
1,396
star
5

UnityBezierSolution

A bezier spline solution for Unity 3D with some utility functions (like travelling the spline with constant speed/time)
C#
1,153
star
6

UnitySimpleFileBrowser

A uGUI based runtime file browser for Unity 3D (draggable and resizable)
C#
844
star
7

UnityDynamicPanels

Draggable, resizable, dockable and stackable UI panel solution for Unity 3D
C#
735
star
8

UnityNativeCamera

A native Unity plugin to take pictures/record videos with device camera on Android & iOS
C#
605
star
9

UnityRuntimePreviewGenerator

Generate preview textures (thumbnails) for your GameObject's or materials on the fly in Unity
C#
304
star
10

UnityNativeFilePicker

A native Unity plugin to import/export files from/to various document providers on Android & iOS
C#
277
star
11

UnityInspectPlus

Speeding up your Inspector workflow in Unity 3D
C#
254
star
12

UnityImageCropper

A uGUI based image cropping solution for Unity 3D
C#
207
star
13

UnityAndroidRuntimePermissions

A native Unity plugin to handle runtime permissions on Android M+
C#
194
star
14

UnityRuntimeSceneGizmo

Interactable runtime scene gizmo for uGUI
C#
175
star
15

UnitySimplePatchTool

Unity port of SimplePatchTool library to add patching support to standalone Unity applications
C#
163
star
16

UnitySimpleInput

An improvement over Unity's legacy Input system that allows you to use custom input providers like on-screen joysticks, UI buttons and d-pads
C#
157
star
17

UnityAdjustPivot

Adjust pivot point of an object in Unity without creating an empty parent object
C#
149
star
18

Unity360ScreenshotCapture

A simple script to capture 360ยฐ screenshots in-game with Unity
C#
142
star
19

SimplePatchTool

C# library for patching standalone applications with binary diff and self patching support
C#
132
star
20

UnityTextToTextMeshProUpgradeTool

Upgrade Text, InputField, Dropdown and TextMesh objects to their TextMesh Pro variants in Unity
C#
113
star
21

DownloadLinkGeneratorForGoogleDrive

Create list of files and their download links in a Google Driveโ„ข folder
HTML
109
star
22

UnityIonicIntegration

A guide to integrating Unity 3D content into an Ionic app and sending messages between them (for Android & iOS)(tested with Vuforia plugin)
Objective-C++
104
star
23

UnityMobileLocalizedAppTitle

Localize your Unity app's name and/or icon on Android & iOS
C#
102
star
24

UnityGridFramework

Open source Grid Framework for creating grid-based levels easily in Unity 3D
C#
94
star
25

UnitySimpleGDPRConsent

A Unity plugin to present GDPR consent dialogs to the users
C#
93
star
26

UnityTextureOps

A basic image processing plugin for Unity
C#
87
star
27

UnityChoiceOfGamesSaveManager

Save manager for 'Choice of Games' on Steam - Created with Unity 3D
C#
76
star
28

UnitySpeechToText

A native Unity plugin to convert speech to text on Android & iOS
C#
70
star
29

UnityRuntimeTexture

An abstraction layer on top of Texture2D.LoadImage to create Texture2D objects at runtime from raw PNG/JPEG data in Unity
C#
62
star
30

UnityDashedSpriteShape

Creating dashed (dotted) 2D Sprite Shapes in Unity
ShaderLab
62
star
31

UnityMobileRemoteControl

Control your Windows device from your phone
C#
59
star
32

UnityEditorGoogleDriveIntegration

Access your Google Driveโ„ข files from within Unity editor
C#
48
star
33

UnityHexicGame

Hexic puzzle game made with Unity 3D
ShaderLab
36
star
34

UnityGenericPool

A simple generic pooling script for Unity3D with a helper class
C#
36
star
35

UnitySpinningLoadingBars

3 different spinning loading bar prefabs for Unity's UI system
28
star
36

UnityFlatColorPalettes

A number of flat color palettes for Unity 3D
26
star
37

UnityEveryplaySaveToLocal

A helper script to save captured Everyplay videos to local file system on Android & iOS
Objective-C++
15
star
38

UnityOrderedUpdate

Receive Update callback(s) from anywhere and in any order in Unity!
C#
15
star
39

UnityAndroidStreamingAssets

A helper script to extract StreamingAssets to local file system on Unity Android
C#
10
star
40

DownloadLinkGeneratorForDropbox

Create list of files and their download links in a Dropbox folder
HTML
6
star
41

SecondHand

Global Game Jam entry
C#
5
star
42

GeometricSketchpadProject

Bilkent CS102 Course Project
Java
4
star
43

GreenHellMods

A number of mods created via ModAPI for Green Hell game
C#
4
star
44

.github

Default GitHub community health files for all my repositories
2
star
45

BubblesProject

Bilkent CS319 Course Project
Java
2
star