Image not be picked in iOS simulator - ios

I am using the below code to get pick image in flutter application, when the code is run on Android it works fine, but when the same code is run on iOS it crashes the app while tapping the button to pick the image.
How should I resolve it?
ERROR I GET
Lost connection to device.
final ImagePicker _picker = ImagePicker();
Future getImage() async {
print("get image");
PickedFile image = await _picker.getImage(source: ImageSource.gallery);
if (image != null) {
setState(() {
final File file = File(image.path);
avatarImageFile = file;
isLoading = true;
});
}
}
info.plist properties

You have to add the below permission in Info.plist file in XCode.
Camera :
Key : Privacy - Camera Usage Description
Value : $(PRODUCT_NAME) camera use
Photo :
Key : Privacy - Photo Library Usage Description
Value : $(PRODUCT_NAME) photo use

Related

Get Permission to Scan Barcodes on iOS with Flutter

I'm using qr_code_scanner to scan barcodes in my Flutter app and it works fine for Android, but when I try to scan for iOS a pop-up appears and looks like:
I'm using the descriptions Flutter code that looks like the following:
QRView(
key: qrKey,
onQRViewCreated: (controller) => {
controller.scannedDataStream.listen((code) async {
...
})
})
And in my Info.plist file I have the following fields:
<key>io.flutter.embedded_views_preview</key>
<true/>
<key>NSCameraUsageDescription</key>
<string>Camera permission is required to scan QR codes.</string>
However even with these settings set, I can't seem to figure out how to have access to the camera. Thanks for any help.
Update
I followed #EvgeniyTrubilo suggestion and used permission_handler to request permission using the following code:
void getCameraPermission() async {
print(await Permission.camera.status); // prints PermissionStatus.granted
var status = await Permission.camera.status;
if (!status.isGranted) {
final result = await Permission.camera.request();
if (result.isGranted) {
setState(() {
canShowQRScanner = true;
});
} else {
Scaffold.of(context).showSnackBar(
SnackBar(content: Text('Please enable camera to scan barcodes')));
Navigator.of(context).pop();
}
} else {
setState(() {
canShowQRScanner = true;
});
}
}
The first time this code was executed it successfully requested permission to access camera, and once permission was granted, the same error showed up. Sequential tries the print statement at the top of the above function said the Permission was granted??
Update 2x
Just realized you can mock the camera in an iOS simulator like you can on Android. I will try this on an actual device and update.
You can use permission_handler. With this, you could ask for camera permission before build QRView. Of course, you should build QRView after camera permission is enabled.
I'm not sure it would be right solution for your issue, but I think that would be an awesome improvement.

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);
}
}

iOS 11 application crashes when trying to add attachment from camera

I have an application that crashes when the user tries to add an attachment from the camera (however it doesn't crash when they opt to load the attachment from their Photo Library).
Here's the method that gets called when an option (either Camera or Photo Library) is selected:
public void AddMedia(UIImagePickerControllerSourceType type)
{
_imagePicker = new UIImagePickerController();
// set our source to the photo library
_imagePicker.SourceType = type;
// set what media types
_imagePicker.MediaTypes = UIImagePickerController.AvailableMediaTypes(type);
_imagePicker.FinishedPickingMedia += Handle_FinishedPickingMedia;
_imagePicker.Canceled += (sender, evt) =>
{
Console.WriteLine("picker cancelled");
_imagePicker.DismissViewController(false, () =>
{
});
};
//PresentModalViewController is depreciated in iOS6 so we use PresentViewController
Parent.PresentViewController(_imagePicker, true, null);
}
And this is the line where it crashes:
_imagePicker.SourceType = type;
Why would it crash when setting it to Camera but not Photo Library? Does it have something to do with how the enum is ordered (Photo Library = 0, Camera = 1, Saved Photos Album = 2)?
Are you trying to reproduce it on simulator? Because you don't have an access to camera on it.

Launching safari with an image or saving to camera roll issues

I've downloaded an image from a web service and either need to open the image within safari or save it to the camera roll. I've tried to open the image in Safari, but safari doesn't open.
var safari = UIApplication.SharedApplication;
var uri = new NSUrl(path); // where the image is saved to
safari.OpenUrl(uri);
This compiles, but Safari doesn't launch
The code I have for saving to the camera roll is this
PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(() =>
{
using (var pool3 = new NSAutoreleasePool())
{ pool3.InvokeOnMainThread(delegate ()
{ PHAssetChangeRequest.FromImage((UIImage)UIImage.FromFile(path));
});
}
}, (t, err) =>
{
if (!t)
{
using (var pool1 = new NSAutoreleasePool())
{
pool1.InvokeOnMainThread(delegate () {
var alert = new UIAlertView("Error saving file", "An error has occured saving your photo to the camera roll", null, "OK");
alert.Show();
};
}
else
{
using (var pool2 = new NSAutoreleasePool())
{
pool2.InvokeOnMainThread(delegate (){
var alert = new UIAlertView("Image saved", "Your image has been saved to the camera roll", null, "OK");
alert.Show();
});
};
}
});
which crashes and burns (the correct permissions have been set)
I'm at a loss as to why neither of these work as they seem to be correct.
You can't open a local path with safari, that isn't allowed on iOS (apps are sandboxed) so you'll need to use either a remote URL or have your own UIWebView or WKWebView or a SFSafariViewController to display that image in a safari like experience. Here is a blog post in the Xamarin Site about the subject.
Also here is a nice recipe in the Xamarin site to save a photo into the camera roll, you can do your own solution based on it.
Hope this helps!

Resources