yasirkula / UnityNativeFilePicker

A native Unity plugin to import/export files from/to various document providers on Android & iOS
MIT License
277 stars 30 forks source link

Unity Native File Picker Plugin

Available on Asset Store: https://assetstore.unity.com/packages/tools/integration/native-file-picker-for-android-ios-173238

Forum Thread: https://forum.unity.com/threads/native-file-picker-for-android-ios-open-source.912890/

Discord: https://discord.gg/UJJt549AaV

GitHub Sponsors ☕

This plugin helps you import/export files from/to various document providers on Android & iOS (other platforms aren't supported). On iOS, it uses UIDocumentPickerViewController which has the following requirements:

NOTE: custom file extensions are supported on iOS only.

INSTALLATION

There are 5 ways to install this plugin:

Android Setup

NativeFilePicker no longer requires any manual setup on Android.

iOS Setup

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

a. Automated Setup for iOS

b. Manual Setup for iOS

FAQ

You can't. The abstraction layers used on each platform deliberately don't return raw file paths.

Only Android & iOS platforms are supported. Editor functionality is for preview purposes only and uses Unity's Editor-only API.

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.* { *; }

See: https://forum.unity.com/threads/native-file-picker-for-android-ios-open-source.912890/page-3#post-8987518

Make sure that you've set the Write Permission to External (SDCard) in Player Settings.

Declare the WRITE_EXTERNAL_STORAGE permission manually in your Plugins/Android/AndroidManifest.xml file with the tools:node="replace" attribute as follows: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" tools:node="replace"/> (you'll need to add the xmlns:tools="http://schemas.android.com/tools" attribute to the <manifest ...> element).

HOW TO

A. Importing Files

NativeFilePicker.PickFile( FilePickedCallback callback, params string[] allowedFileTypes ): prompts the user to pick a file from the available document providers.

NativeFilePicker.PickMultipleFiles( MultipleFilesPickedCallback callback, params string[] allowedFileTypes ): prompts the user to pick one or more files.

NOTE: on iOS, imported files will automatically be deleted by the OS after the application is closed. If you need the files to persist, move them to Application.persistentDataPath.

B. Exporting Files

NativeFilePicker.ExportFile( string filePath, FilesExportedCallback callback = null ): prompts the user to export a file to the available document providers.

NativeFilePicker.ExportMultipleFiles( string[] filePaths, FilesExportedCallback callback = null ): prompts the user to export one or more files.

All of these functions return a NativeFilePicker.Permission value. More details about it is available below.

C. Runtime Permissions

Beginning with 6.0 Marshmallow, Android apps must request runtime permissions before accessing certain services. There are two functions to handle permissions with this plugin:

NativeFilePicker.Permission NativeFilePicker.CheckPermission( bool readPermissionOnly = false ): checks whether the app has access to the document providers or not.

NativeFilePicker.Permission is an enum that can take 3 values:

NativeFilePicker.Permission NativeFilePicker.RequestPermission( bool readPermissionOnly = false ): requests permission to access the document providers from the user and returns the result. It is recommended to show a brief explanation before asking the permission so that user understands why the permission is needed and doesn't click Deny or worse, "Don't ask again". Note that the PickFile/PickMultipleFiles and ExportFile/ExportMultipleFiles functions call RequestPermission internally and execute only if the permission is granted (the result of RequestPermission is also returned).

void NativeFilePicker.RequestPermissionAsync( PermissionCallback callback, bool readPermissionOnly = false ): Asynchronous variant of RequestPermission. Unlike RequestPermission, this function doesn't freeze the app unnecessarily before the permission dialog is displayed. So it's recommended to call this function instead.

Task<NativeFilePicker.Permission> NativeFilePicker.RequestPermissionAsync( bool readPermissionOnly = false ): Another asynchronous variant of RequestPermission (requires Unity 2018.4 or later).

NativeFilePicker.OpenSettings(): opens the settings for this app, from where the user can manually grant the Storage permission in case current permission state is Permission.Denied.

NOTE: on iOS, no permissions are needed and thus, these functions will always return Permission.Granted.

C. Other Functions

bool NativeFilePicker.CanPickMultipleFiles(): returns true if importing/exporting multiple files is supported (Android 18+ and iOS 11+).

bool NativeFilePicker.CanExportFiles(): returns true if exporting a single file is supported (Android 19+ and iOS 8+).

bool NativeFilePicker.CanExportMultipleFiles(): returns true if exporting multiple files is supported (Android 21+ and iOS 11+).

bool NativeFilePicker.IsFilePickerBusy(): returns true if the user is currently importing/exporting files. In that case, another PickFile, PickMultipleFiles, ExportFile or ExportMultipleFiles request will simply be ignored.

string NativeFilePicker.ConvertExtensionToFileType( string extension ): converts a file extension to its corresponding MIME on Android and UTI on iOS (don't include the period in extension, i.e. use png instead of .png). Throws an exception if "*" or "*/*" is passed to extension (to allow all file types, don't pass anything to PickFile function's allowedFileTypes parameter).

EXAMPLE CODE

The following code has 4 functions:

private string pdfFileType;

void Start()
{
    pdfFileType = NativeFilePicker.ConvertExtensionToFileType( "pdf" ); // Returns "application/pdf" on Android and "com.adobe.pdf" on iOS
    Debug.Log( "pdf's MIME/UTI is: " + pdfFileType );
}

void Update()
{
    if( Input.GetMouseButtonDown( 0 ) )
    {
        // Don't attempt to import/export files if the file picker is already open
        if( NativeFilePicker.IsFilePickerBusy() )
            return;

        if( Input.mousePosition.x < Screen.width / 3 )
        {
            // Pick a PDF file
            NativeFilePicker.Permission permission = NativeFilePicker.PickFile( ( path ) =>
            {
                if( path == null )
                    Debug.Log( "Operation cancelled" );
                else
                    Debug.Log( "Picked file: " + path );
            }, new string[] { pdfFileType } );

            Debug.Log( "Permission result: " + permission );
        }
        else if( Input.mousePosition.x < Screen.width * 2 / 3 )
        {
#if UNITY_ANDROID
            // Use MIMEs on Android
            string[] fileTypes = new string[] { "image/*", "video/*" };
#else
            // Use UTIs on iOS
            string[] fileTypes = new string[] { "public.image", "public.movie" };
#endif

            // Pick image(s) and/or video(s)
            NativeFilePicker.Permission permission = NativeFilePicker.PickMultipleFiles( ( paths ) =>
            {
                if( paths == null )
                    Debug.Log( "Operation cancelled" );
                else
                {
                    for( int i = 0; i < paths.Length; i++ )
                        Debug.Log( "Picked file: " + paths[i] );
                }
            }, fileTypes );

            Debug.Log( "Permission result: " + permission );
        }
        else
        {
            // Create a dummy text file
            string filePath = Path.Combine( Application.temporaryCachePath, "test.txt" );
            File.WriteAllText( filePath, "Hello world!" );

            // Export the file
            NativeFilePicker.Permission permission = NativeFilePicker.ExportFile( filePath, ( success ) => Debug.Log( "File exported: " + success ) );

            Debug.Log( "Permission result: " + permission );
        }
    }
}

// Example code doesn't use this function but it is here for reference. It's recommended to ask for permissions manually using the
// RequestPermissionAsync methods prior to calling NativeFilePicker functions
private async void RequestPermissionAsynchronously( bool readPermissionOnly = false )
{
    NativeFilePicker.Permission permission = await NativeFilePicker.RequestPermissionAsync( readPermissionOnly );
    Debug.Log( "Permission result: " + permission );
}