I built a Xamarin App: Android, and am trying to allow the user to be able to set an avatar. using Xamarin Essentials Media Picker I am trying to either capture an image or select one. But each time the application runs either method, it works then crashes the app before an image is selected or captures. The funny thing is it sometimes works but hardly ever.
I tried a lot of ways to figure out what is going on but without an actual error to work with, I am getting nowhere.
I am using the MVVM design pattern. My Code:
private async Task TakePicture()
{
try
{
var photo = await MediaPicker.PickPhotoAsync();
if (photo != null)
{
await App.UserManager.UpdateAvatarAsync(photo);
RenderImages();
}
}
catch (global::System.Exception ex)
{
await AppShell.Current.DisplayAlert("Oops", "Something went wrong and its not your fault", "Okay");
}
}
You could use the ways below to piack the photo.
1. Use the Xam.Plugin.Media
. You could install from the NuGet. Do not forget to checkthe location you save the photos and ask for the runtime permission.
The code below shows how to pick the photo from Camera and set to the image control.
pickPhoto.Clicked += async (sender, args) =>
{
if (!CrossMedia.Current.IsPickPhotoSupported)
{
DisplayAlert("Photos Not Supported", ":( Permission not granted to photos.", "OK");
return;
}
var file = await Plugin.Media.CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions
{
PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium,
});
if (file == null)
return;
image.Source = ImageSource.FromStream(() =>
{
var stream = file.GetStream();
file.Dispose();
return stream;
});
};
2. Use the dependency service.
[assembly: Dependency(typeof(PhotoPickerService))]
namespace DependencyServiceDemos.Droid
{
public class PhotoPickerService : IPhotoPickerService
{
public Task<Stream> GetImageStreamAsync()
{
// Define the Intent for getting images
Intent intent = new Intent();
intent.SetType("image/*");
intent.SetAction(Intent.ActionGetContent);
// Start the picture-picker activity (resumes in MainActivity.cs)
MainActivity.Instance.StartActivityForResult(
Intent.CreateChooser(intent, "Select Photo"),
MainActivity.PickImageId);
// Save the TaskCompletionSource object as a MainActivity property
MainActivity.Instance.PickImageTaskCompletionSource = new TaskCompletionSource<Stream>();
// Return Task object
return MainActivity.Instance.PickImageTaskCompletionSource.Task;
}
}
}
You could download the source file from the link below. https://learn.microsoft.com/en-us/samples/xamarin/xamarin-forms-samples/dependencyservice/