I'm using Xamarin Essentials MediaPicker (v1.7.3) on my Xamarin Forms 5 app and it just freezes and eventually crashes the app on iOS but works perfectly fine on Android.
My app uses the MVVM
pattern so I have an ImageButton
that's wired to a method in my view model and the code for that method looks like this:
async Task Add_Image_Tapped()
{
try
{
var photosPermission = await Permissions.CheckStatusAsync<Permissions.Photos>();
var cameraPermission = await Permissions.CheckStatusAsync<Permissions.Camera>();
if (photosPermission != PermissionStatus.Granted || photosPermission != PermissionStatus.Restricted)
photosPermission = await Permissions.RequestAsync<Permissions.Photos>();
if (cameraPermission != PermissionStatus.Granted || cameraPermission != PermissionStatus.Restricted)
cameraPermission = await Permissions.RequestAsync<Permissions.Camera>();
if ((photosPermission == PermissionStatus.Granted
|| photosPermission == PermissionStatus.Restricted)
&& (cameraPermission == PermissionStatus.Granted
|| cameraPermission == PermissionStatus.Restricted))
await HandleImagePicker();
}
catch(Exception e)
{
throw new Exception(e.Message);
}
}
And if the permissions check out fine, here's the method that handles the image pick up:
private async Task HandleImagePicker()
{
try
{
var filePath = string.Empty;
var fileName = string.Empty;
MainThread.BeginInvokeOnMainThread(() => {
var result = MediaPicker.PickPhotoAsync(new MediaPickerOptions
{
Title = "Pick Image"
}).Result;
if (result == null)
return;
filePath = result.FullPath;
fileName = result.FileName;
});
if (!string.IsNullOrEmpty(filePath) && !string.IsNullOrEmpty(fileName))
{
// Do something with the image
}
}
catch(Exception e)
{
throw new Exception(e.Message);
}
}
I'm using Xamarin Forms 5.0.0.2401
, Xamarin Community Toolkit 2.0.2
and Xamarin Essentials 1.7.3
. I also have the following permissions in my Info.plist
:
<key>NSCameraUsageDescription</key>
<string>MyApp would like to access your camera</string>
<key>NSMicrophoneUsageDescription</key>
<string>MyApp would like to access your microphone</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>MyApp would like to access your photo library</string>
<key>NSPhotoLibraryAddUsageDescription</key>
<string>MyApp would like to access your photo library</string>
I also initialize Xamarin Essentials in AppDelegate
FinishedLaunching()
method as below:
Xamarin.Essentials.Platform.Init(() => new UIViewController());
Any idea what maybe the issue here?
UPDATE:
The above code reflects the current code I have after making changes based on suggestions such as using the main thread.
Currently, if I run the app on iOS Simulator on a Mac, it literally hangs forever. Never throws an exception or crashes.
If I run it on a real device i.e. iPhone Xs, it will hang for quite a while and eventually crash the whole app.
As mentioned earlier, it all works perfectly fine on Android.