Press "Enter" to skip to content

Getting device media and show it using Xamarin Forms

A few months ago I wrote an article about selecting multiple images/videos in Xamarin Forms, this sample works perfectly when you are using the default gallery design. But what happens if you want to do your own custom gallery design? For this use case, we have two options:

1-Create a custom gallery using native platform APIs and integrate it in Xamarin Forms with a custom renderer or native embedding.

2-Create platform services using native APIs to get all the media and show it using Xamarin Forms.

This article is based on option number 2, since we will get all the images/videos and then use a Xamarin Forms UI to show our media.

The result will be the following:

Let’s start by getting the media

1. In your Forms project, create a IMediaService interface to define the public methods and properties for our media service. Also create a MediaAsset class that will represent our media (video/images)

2. In your iOS project, create a MediaService class that implements IMediaService interface.

3. In your Info.plist file add the “Photo Library Additions Usage Description” and “Photo Library Usage Description” permissions

4. In your Android project, create a MediaService class that implements IMediaService interface.

Important:

– Make sure to install the Plugin.CurrentActivity and initialize it in the MainApplication class.

– Add this PermissionUtil class to check the permissions

– Add Acr.UserDialog that is being used to show alerts.

Let’s show the media in Xamarin Forms

To show the media in Xamarin Forms we used the FlowListView library. Also used glide to optimize image loading on Android.

In the ViewModel we call our MediaService to get the media.

Extra: 

When you tap an image/video it navigates to a detail page to show the images in fullscreen mode and reproduce videos. In case you want to add this, you can use the following resources:

You can check the full source code here.

Happy media!