Xamarin.forms iOS crashes when trying to take video. Cannot debug - ios

I have this issue where I want to make a video using the montemagno library:
private async void CreateVideo()
{
await CrossMedia.Current.Initialize();
if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
{
DisplayAlert("No Camera", ":( No camera available.", "OK");
return;
}
videoFile = await CrossMedia.Current.TakeVideoAsync(new Plugin.Media.Abstractions.StoreVideoOptions
{
DesiredLength = TimeSpan.FromSeconds(Constants.VIDEOLENGTH),
Quality = VideoQuality.Low,
CompressionQuality = 0
});
if (videoFile == null)
return;
//await DisplayAlert("File Location", videoFile.Path, "OK");
btn_delVideo.IsVisible = true;
grid_makeVideo.IsVisible = false;
videoStream = Converters.StreamToByteArray(videoFile.GetStream());
isVideoSet = true;
bx_reset.IsVisible = false;
btn_delVideo.IsVisible = true;
await CrossMediaManager.Current.Play(videoFile.Path);
}
This code works perfectly on android.
On iOS it crashes in production.
I cannot debug this code because it returns. The simulator does NOT have a camera, and therefore can't proceed.
I tried deploying to a real iPhone, but codesigning always failes and those provisioning profiles are the worst in the world.
I know that it at least gets to the point where it displays "no camera" so the initialise function seems to work. Therefore I belelive the issue is at TakeVideoAsync().
It crashes before even showing any camera.
I could really need some help here.

Make sure to have all the permissions set. AND DONT FORGET MICROPHONE USE ;-)

Related

Flutter: 'Lost connection to device.' second time using image_picker to select photo from gallery on iOS

I am developing a mobile app in flutter that requires the user to select an image from the gallery.
I am using image_picker: ^0.6.7+11 and here is my code:
if (await Permission.photos.request().isGranted) {
try {
final image =
await ImagePicker().getImage(source: ImageSource.gallery);
if (image != null) {
photo.clearData();
File _image = File(image.path);
photo.addOriginal(_image);
} else {
print('no image selected');
}
} on PlatformException catch (e) {
print('Platform exception $e');
} catch (e) {
print('Unknown error: $e');
}
}
In the android emulator, everything works fine. In the iOS simulator I am able to choose an image, but if I try to choose a second image then the app crashes and 'Lost connection to device.' is printed in the run tab - but no errors.
Question: How can I fix this so that I can go back to the gallery and select a different image as many times as I want on iOS?
When debugging I have come across this:
PlatformException(multiple_request, Cancelled by a second request, null, null)
I have gone through as many similar questions as I can find on here, GitHub etc... I have:
upgraded flutter
upgraded pub files
flutter clean
clean and build in Xcode
added 'imageCache.clear()' in flutter code
invalidate caches and restart in android studio
flutter doctor -v : no issues found
checked the permissions (info.plist and added permission_handler package)
restarted the simulator
erased all contents and settings in simulator
debugging with breakpoints weirdly stops the problem from happening a few times then after a few selections the app crashes again ¯\(ツ)/¯
I'm sure its something straight forward but I feel like I have exhausted all my options and not sure where to go from here.
Your code is right and it is a simulator problem,if you want to test it on IOS, you have to test on a real IPhone and here is a snippet on how properly you can do it:
final imagePicker = ImagePicker();
PickedFile pickedFile;
if (fileType == FileType.Camera) {
// Camera Part
pickedFile = await imagePicker.getImage(
source: ImageSource.camera,
maxWidth: 480,
maxHeight: 640,
imageQuality: 25, // pick your desired quality
);
setState(() {
if (pickedFile != null) {
_storedFile = File(pickedFile.path);
} else {
print('No image selected.');
return;
}
});
} else if (fileType == FileType.Gallery) {
// Gallery Part
pickedFile = await imagePicker.getImage(
source: ImageSource.gallery,
maxWidth: 480,
maxHeight: 640,
imageQuality: 25,
);
} else {
print('No image selected.');
return;
}
});
}
and don't forget the enum when the user picks the way he wants to get the image:
enum FileType {
Gallery,
Camera,
Video,
}
Edit:
whenever you add a package that depends on native code, you should restart the whole app build b stopping your build and restarting it again so the native code compiles well, don't forget to restart before putting this package in your pubspec.yaml
Hope it helps, if this answer helped you, don't forget to mark as answered and upvote it please.

Xamarin.Forms: iOS Camera doenst work, Gallery works ok (Android, both works)

since my iPhone Simulator has no camera, it is impossible to debug this on my simulator. But I have a physical device, however, with those stupid provisioning profiles, I am only able to send release versions to my actual iPhone 7, which means it doesnt return debug info.
However, with the help of TRY CATCH I was able to pinpoint when the actual iPhone crashes: it is this line of code:
file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
{
Directory = "Sample",
Name = "test.jpg"
});
The whole code looks like this:
await CrossMedia.Current.Initialize();
Plugin.Media.Abstractions.MediaFile file = null;
try
{
file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
{
Directory = "Sample",
Name = "test.jpg"
});
}
catch
{
await DisplayAlert("1", ":( No camera available.", "OK");
}
if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
{
await DisplayAlert("No Camera", ":( No camera available.", "OK");
return;
}
if (file == null)
return;
Since it runs into the catch block here, I know it is the abolev line that throws the error.
This is the james montamagno plugin.
Can you guys help me out here? Might this be a permission problem?
Thank you!
Adding this to info.plist:
<key>NSCameraUsageDescription</key>
<string>This app needs access to the camera to take photos.</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>This app needs access to photos.</string>
Solved the issue!

Xamarin forms: jamesmontemagno/MediaPlugin: Selected picture is rotating when added to UI in IOS app

I followed this blog for taking photos from the gallery and camera. But the selected picture is showing in right rotated form when it comes to the UI in IOS. Problem only occurs when using the camera and I have no issues with the gallery. This feature is working fine in android and UWP.
Screenshot added below:
Code of Camera:
async void CameraClick()
{
try
{
await CrossMedia.Current.Initialize();
if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
{
await DisplayAlert("Camera", "No camera available.", "OK");
return;
}
_mediaFile = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
{
Directory = "Sample",
Name = "test.jpg",
AllowCropping = true
});
if (_mediaFile == null)
return;
profileImage.Source = ImageSource.FromStream(() =>
{
isPicture = true;
return _mediaFile.GetStream();
});
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Exception:>" + ex);
}
}
Device : IOS SE
Version of the media plugin: 3.1.1
Control I am using to display the image : Xam.plugins.Forms.Imagecircle 2.0.2(For android and UWP I am using 1.8.1)
Gallery pictures are working fine and the issue is only when taking pictures using the camera. No issues in android and UWP part.
Cause:
This is a common experience even outside of Xamarin. It is caused by iOS.
A UIImage has a property imageOrientation, which instructs the
UIImageView and other UIImage consumers to rotate the raw image data.
There's a good chance that this flag is being saved to the exif data
in the uploaded jpeg image, but the program you use to view it is not
honoring that flag.
Solution:
In the Issues part in jamesmontemagno/MediaPlugin in Github, there are several issues like the problem you meet. Seems using GetStreamWithImageRotatedForExternalStorage will fix this issue.
You can refer to:
https://github.com/jamesmontemagno/MediaPlugin/issues/333
In another way, you can rotate the image yourself.
Here are some links that might help you:
iOS Image Orientation has Strange Behavior
iOS UIImagePickerController result image orientation after upload
iOS: Image get rotated 90 degree after saved as PNG representation data
I faced this problem in the last few months on iOS.
The solution for this is add one more line in your code that is:- SaveMetaData = false,
async void CameraClick()
{
try
{
await CrossMedia.Current.Initialize();
if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
{
await DisplayAlert("Camera", "No camera available.", "OK");
return;
}
_mediaFile = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
{
Directory = "Sample",
Name = "test.jpg",
AllowCropping = true,
SaveMetaData = false
});
if (_mediaFile == null)
return;
profileImage.Source = ImageSource.FromStream(() =>
{
isPicture = true;
return _mediaFile.GetStream();
});
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Exception:>" + ex);
}
}

How to take photo continuously using XLabs

Currently I'm developing a cross-platform app using Shared Library that able to take photos. I'm using XLabs.Forms V2.0.5782 package to do this app. I successfully developed this simple app but it only allows me to take one picture at a time.
I messed around with the codes and I managed to take multiple pictures but the problem is, the camera will be closed when I clicked 'Use Photo' and reopen again to take the next photo. What I wanted is, when I clicked 'Use Photo', the camera will reopen on the spot instead of closing and reopen.
Here's the code I did to take multiple pictures but I know it is not the right way to do it. It is in button clicked event.
IDevice device = Resolver.Resolve<IDevice>();
IMediaPicker media = device.MediaPicker;
//More codes here
async void TakePicture(object sender, System.EventArgs e)
{
var options = new CameraMediaStorageOptions()
{
PercentQuality = 50,
DefaultCamera = CameraDevice.Rear,
MaxPixelDimension = 250
};
var cancel = false;
while (!cancel)
{
await media.TakePhotoAsync(options).ContinueWith(t =>
{
if (t.IsFaulted) //If there's an error when taking photos
{
DisplayAlert("Error", "An error occurred when taking photo.\nPlease try again.", "OK");
}
else if (t.IsCanceled) //When the user click 'Cancel'
{
cancel = true;
}
else //When the user click 'Use Photo' - Here's the part where the camera will close and reopen until user click 'Cancel'
{
var img = ImageSource.FromStream(() => t.Result.Source);
picList.Add(img);
}
});
}
if (picList.Count > 0)
{
scrollParent.IsVisible = true;
imageScroll.Children.Clear();
foreach (var pl in picList)
{
var image = new Image()
{
Source = pl,
HeightRequest = 150,
HorizontalOptions = LayoutOptions.Start,
Aspect = Aspect.AspectFit,
Margin = new Thickness()
{
Right = 10
}
};
imageScroll.Children.Add(image);
}
}
}
Is it possible for me to take multiple pictures with XLabs.Forms and is there a proper way? I've search everywhere but found nothing about this. Any help will be much appreciated. Thanks!
Note:
I'm using Visual Studio for Mac Version Preview 9 (7.0 build 2943)
I've only tested on iPhone running iOS 10.2. Have not tested on Android device yet
Here's a gif showing an example of my app. I think this will make you guys have a better understanding of what I want and what is happening
Please note that 3 photos are taken in this example. The camera opens up four times. After taking each photo, I clicked 'Use Photo' on the bottom right and when the camera open on the 4th time, I clicked 'Cancel' on the bottom left to stop the loop
Thank you!

Strange behaviour of Geolocator.GetGeopositionAsync() after first launch

I'm writing Windows Phone 8 app that needs to get location of device (do not track changes, just get location). I added next code to the method OnNavigatedTo() of my start page but after launching app, the progress indicator does not hide even after 10 seconds timeout. But if I navigate to another page and then go back, everything works fine. This happens on the emulator, I don't have a real device. What am I doing wrong?
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
if(_geoPosition == null)
{
try
{
var geolocator = new Geolocator();
geolocator.DesiredAccuracyInMeters = 50;
_progressIndicator = new ProgressIndicator
{
IsIndeterminate = true,
Text = "Getting current location, please wait...",
IsVisible = true
};
SystemTray.SetIsVisible(this, true);
SystemTray.SetProgressIndicator(this, _progressIndicator);
_geoPosition = await geolocator.GetGeopositionAsync(TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(10));
_progressIndicator.IsVisible = false;
SystemTray.SetIsVisible(this, false);
}
catch (UnauthorizedAccessException)
{
MessageBox.Show("Location is disabled in phone settings");
}
}
}
Thanks!
UPD: just tried to add this code to empty project and it works fine. Tried to comment out some parts of OnNavigatedTo that I did not include to the snippet and found out that the reason somewhere in initialization of data source for this page. I'm sorry for false alarm.
Your code works fine for me, try the classic restart VS and the projecy!
The code should work, tested it with an emulator and a device (nokia 820).
Best of luck

Resources