Xamarin.MediaGallery.Permision 2.2.0-preview

This is a prerelease version of Xamarin.MediaGallery.Permision.
There is a newer version of this package available.
See the version list below for details.
dotnet add package Xamarin.MediaGallery.Permision --version 2.2.0-preview                
NuGet\Install-Package Xamarin.MediaGallery.Permision -Version 2.2.0-preview                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Xamarin.MediaGallery.Permision" Version="2.2.0-preview" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Xamarin.MediaGallery.Permision --version 2.2.0-preview                
#r "nuget: Xamarin.MediaGallery.Permision, 2.2.0-preview"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install Xamarin.MediaGallery.Permision as a Cake Addin
#addin nuget:?package=Xamarin.MediaGallery.Permision&version=2.2.0-preview&prerelease

// Install Xamarin.MediaGallery.Permision as a Cake Tool
#tool nuget:?package=Xamarin.MediaGallery.Permision&version=2.2.0-preview&prerelease                

MediaGallery for Xamarin and MAUI

header

NuGet Badge NuGet downloads license Xamarin.MediaGallery on fuget.org YouTube Video Views

This plugin is designed for picking and saving photos and video files from the native gallery of Android and iOS devices and capture photo.

"Buy Me A Coffee"

FAQ

Please read this file and see samples before creating an issue.

Q: I can't build Xamarim.MediaGallery solution. Why?

A: Sorry, it became very difficult after adding support for MAUI, but you can build Xamarim.MediaGallery.Sample.sln or Xamarim.MediaGallery.Sample.Maui.sln

Q: Why does a image have wrong orientation?

A: This is correct behavior. The plugin returns images without any changes, See metadata

Q: How do I get FilePath?

A: It is not possible. But you can copy a file to a cache directory

Q: How does Xamarin.MediaGallery work on a PopupPage from Rg.Plugins.Popup?

A: Fine! But you need to initialize the plugin on iOS. See taht sample code

Q: Why an error thrown when picking a image on a iOS simulator?

A: This issue is on Apple side

Available Platforms

Platform Minimum OS Version
Android 5.0
iOS 11.0

TargetFrameworks

  • net6.0-ios, net6.0-android31.0, net6.0-android32.0, net6.0-android33.0
  • netstandard2.0, Xamarin.iOS10, MonoAndroid10.0, MonoAndroid11.0, MonoAndroid12.0, MonoAndroid13.0

Getting started

You can just watch the Video that @jfversluis published

Migration to 2.X.X version

Android

In the Android project's MainLauncher or any Activity that is launched, this plugin must be initialized in the OnCreate method:

protected override void OnCreate(Bundle savedInstanceState)
{
    //...
    base.OnCreate(savedInstanceState);
    NativeMedia.Platform.Init(this, savedInstanceState);
    //...
}

iOS (Optional)

In the iOS project's AppDelegate that is launched, this plugin can be initialized in the FinishedLaunching method:

public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
    NativeMedia.Platform.Init(GetTopViewController);
    global::Xamarin.Forms.Forms.Init();
    LoadApplication(new App());
    return base.FinishedLaunching(app, options);
}

public UIViewController GetTopViewController()
{
    var vc = UIApplication.SharedApplication.KeyWindow.RootViewController;

    if (vc is UINavigationController navController)
        vc = navController.ViewControllers.Last();

    return vc;
}

PickAsync

This method does not require requesting permissions from users

var cts = new CancellationTokenSource();
IMediaFile[] files = null;

try
{
    var request = new MediaPickRequest(1, MediaFileType.Image, MediaFileType.Video)
    {
        PresentationSourceBounds = System.Drawing.Rectangle.Empty,
        UseCreateChooser = true,
        Title = "Select"
    };

    cts.CancelAfter(TimeSpan.FromMinutes(5));

    var results = await MediaGallery.PickAsync(request, cts.Token);
    files = results?.Files?.ToArray();
}
catch (OperationCanceledException)
{
    // handling a cancellation request
}
catch (Exception)
{
    // handling other exceptions
}
finally
{
    cts.Dispose();
}


if (files == null)
    return;

foreach (var file in files)
{
    var fileName = file.NameWithoutExtension; //Can return an null or empty value
    var extension = file.Extension;
    var contentType = file.ContentType;
    using var stream = await file.OpenReadAsync();
    //...
    file.Dispose();
}

This method has two overloads:

  • Task<MediaPickResult> PickAsync(int selectionLimit = 1, params MediaFileType[] types)
  • Task<MediaPickResult> PickAsync(MediaPickRequest request, CancellationToken token = default)

Android

To handle runtime results on Android, this plugin must receive any OnActivityResult.

protected override void OnActivityResult(int requestCode, Result resultCode, Intent intent)
{
   if (NativeMedia.Platform.CheckCanProcessResult(requestCode, resultCode, intent))
   NativeMedia.Platform.OnActivityResult(requestCode, resultCode, intent);
   
   base.OnActivityResult(requestCode, resultCode, intent);
}

If an app has android:targetSdkVersion or greater new Photo picker will be used if possible.

Default behavior
  • When using PickAsync method selectionLimit parameter just sets multiple pick allowed
  • A request to cancel PickAsync method will cancel a task, but the picker UI can remain open until it is closed by the user
  • The use of Title property depends on each device
  • UseCreateChooser property has not been used since version 2.0.0
Photo Picker behavior
  • selectionLimit parameter limits the number of selected media files
  • Title property not used
  • UseCreateChooser property not used

iOS

  • Multi picking is supported since iOS version 14.0+ On older versions, the plugin will prompt the user to select a single file
  • The NameWithoutExtension property on iOS versions before 14 returns a null value if the permission to access photos was not granted
  • Title property not used
  • UseCreateChooser property not used
Presentation Location

When picking files on iPadOS you have the ability to present in a pop over control. This specifies where the pop over will appear and point an arrow directly to. You can specify the location using the PresentationSourceBounds property. Setting this property has the same behavior as Launcher or Share in Xamarin.Essentials.

PresentationSourceBounds property takes System.Drawing.Rectangle for Xamarin or Microsoft.Maui.Graphics.Rect for .net6(MAUI)

Screenshots:

Сapture Photo with Metadata

//...
if (!MediaGallery.CheckCapturePhotoSupport())
    return;

var status = await Permissions.RequestAsync<Permissions.Camera>();

if (status != PermissionStatus.Granted)
    return;

using var file = await MediaGallery.CapturePhotoAsync()

NameWithoutExtension will always return $"IMG_{DateTime.Now:yyyyMMdd_HHmmss}" value.

Android

Open the AndroidManifest.xml file under the Properties folder and add the following inside of the manifest node.

<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" android:required="true" />

If Camera is not required in your application, you can specify false.

<queries>
  <intent>
    <action android:name="android.media.action.IMAGE_CAPTURE" />
  </intent>
</queries>

iOS

In your Info.plist add the following keys:

<key>NSCameraUsageDescription</key>
<string>This app needs access to the camera to take photos.</string>

SaveAsync

//...
var status = await Permissions.RequestAsync<SaveMediaPermission>();

if (status != PermissionStatus.Granted)
    return;

await MediaGallery.SaveAsync(MediaFileType.Video, filePath);

//OR Using a byte array or a stream

await MediaGallery.SaveAsync(MediaFileType.Image, stream, fileName);

//The name or the path to the saved file must contain the extension.

//...

Permission

Add Xamarin.MediaGallery.Permision or Xamarin.MediaGallery.Permision.Maui nuget package to use the SaveMediaPermission

Android

Open the AndroidManifest.xml file under the Properties folder and add the following inside of the manifest node.


<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  • When saving media files, the date and time are appended to the file name

iOS

In your Info.plist add the following keys:


<key>NSPhotoLibraryAddUsageDescription</key>
<string>This app needs access to the photo gallery for saving photos and videos</string>


<key>NSPhotoLibraryUsageDescription</key>
<string>This app needs access to the photo gallery for saving photos and videos</string>

Screenshots

iOS Android - defult Android - Photo Picker
iOS Android Android2
Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed.  monoandroid10.0 is compatible.  monoandroid11.0 is compatible.  monoandroid12.0 is compatible.  monoandroid13.0 is compatible. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed.  xamarinios10 is compatible. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
2.2.1 119,274 2/24/2023
2.2.1-preview 151 2/17/2023
2.2.0 45,206 1/6/2023
2.2.0-preview 246 12/6/2022
2.1.2 22,599 11/28/2022
2.1.2-alpha003 167 11/27/2022
2.1.2-alpha002 166 11/26/2022
2.1.2-alpha001 150 11/23/2022
2.0.0 125,567 12/5/2021
2.0.0-preview4 224 12/4/2021
2.0.0-preview3 5,271 11/23/2021
2.0.0-preview2 345 11/22/2021