How to take photo continuously using XLabs - ios

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!

Related

Xamarin forms geolocator plugin working intermittently

We are trying to use the plugin "Xam.Plugin.Geolocator" in our Xamarin Forms project. The project is currently IOS only.
Our app returns a list of business based on the device users current location. We hit an API to return our JSON formatted list data and the API is functioning correctly.
We would like the list to update whenever the user pulls down, changes tab and when the page initially loads but currently this is only working once or twice in around 100 attempts. I've not found a pattern yet to why it's failing, or indeed when it works.
We set App Properties when the page loads, the tab is selected and the user refreshes like this -
public async void GetLocation()
{
try
{
locator = CrossGeolocator.Current;
if (locator.IsGeolocationAvailable && locator.IsGeolocationEnabled)
{
var position = await locator.GetPositionAsync();
App.Current.Properties["Longitude"] = position.Longitude.ToString();
App.Current.Properties["Latitude"] = position.Latitude.ToString();
}
else
{
await DisplayAlert("Location Error", "Unable to retrieve location at this time", "Cancel");
}
}catch(Exception e)
{
await DisplayAlert("Location Error", "Unable to retrieve location at this time","Cancel");
}
}
We call the above method in the three areas
1) when the page is loaded
public NearbyPage()
{
InitializeComponent();
GetLocation();
SetNearbyBusinesses();
NearbyBusinesses = new List<NearbyBusiness>();
SetViewData();
SetViewVisibility();
}
2) when the tab is clicked
protected override void OnAppearing()
{
base.OnAppearing();
GetLocation();
SetNearbyBusinesses();
NearbyLocationsView.ItemsSource = NearbyBusinesses;
NoLocationsView.ItemsSource = UserMessages;
SetViewVisibility();
}
3) when the user pulls down to refresh
public void RefreshData()
{
if (!CrossConnectivity.Current.IsConnected)
{
NoInternetMessage.IsVisible = true;
return;
}
GetLocation();
NoInternetMessage.IsVisible = false;
SetNearbyBusinesses();
NearbyLocationsView.ItemsSource = NearbyBusinesses;
NoLocationsView.ItemsSource = UserMessages;
SetViewVisibility();
_analyticsService.RecordEvent("Refresh Event: Refresh nearby businesses", AnalyticsEventCategory.UserAction);
}
Can anyone shed some light on what we're doing wrong or have experience with this plugin that can help us resolve this issue?
Thank you
EDIT
By "work", i mean that we'd like it to hit our API with the users current location data and return new results from the API every time the user pulls down to refresh, the page is loaded initially or when they press on a specific tab. Currently it works occasionally, very occasionally.
We can't debug with a phone connected to a macbook, as since we installed the geolocator plugin the app always crashes when connected. The app seems to work ok when deployed to a device, apart from the location stuff. We're currently deploying to test devices via Microsofts Mobile Centre.
Ok, so with the debugger always crashing and being unable to see any stack trace etc we took a few shots in the dark.
We've managed to get this working by adding async to our method signatures down through our code stack. This has resolved the issue and the geo location and refresh is working perfectly.
For example when we changed the above method 3. to refresh the data, it worked perfectly.
public async Task RefreshData()
{
if (!CrossConnectivity.Current.IsConnected)
{
NoInternetMessage.IsVisible = true;
return;
}
GetLocation();
NoInternetMessage.IsVisible = false;
SetNearbyBusinesses();
NearbyLocationsView.ItemsSource = NearbyBusinesses;
NoLocationsView.ItemsSource = UserMessages;
SetViewVisibility();
_analyticsService.RecordEvent("Refresh Event: Refresh nearby businesses", AnalyticsEventCategory.UserAction);
}
We refactored more of that code but adding async was what got it working.
I hope this helps someone else save some time.

Xamarin Forms Plugin.Share not working for unknown reason

We have an image with a gesture recognizer, which calls the CrossShare.Current.Share method. On Android this works fine but on iOS it does not. No error is thrown and there doesn't seem to be any issues, but the share sheet does not appear and from the user's point of view nothing happens when you click the button.
Have I missed some permissions or something somewhere?
This is my method;
async void On_Share(object sender, EventArgs e)
{
if (CrossConnectivity.Current.IsConnected)
{
var message = "Check out this";
var title = "Share this";
await CrossShare.Current.Share(new ShareMessage { Text = message, Title = title}, new ShareOptions { ExcludedUIActivityTypes = new[] { ShareUIActivityType.PostToFacebook } });
}
else
{
NoInternetLabel.IsVisible = true;
}
}
It doesn't throw any errors and I can step through the method fine - it definitely hits the Share line. This problem is only showing on iOS, Android has no issues.
EDIT: Seems to be working fine (we've tried doing it natively as well - without plugin) but now I'm getting Warning: Attempt to present on whose view is not in the window hierarchy!

Air for IOS Webview - apple app review says every tab and/or button launches mobile Safari.?

I pulling my hair out trying to figure out where I have gone wrong.
I created a very simple app for ios that uses webView to load certain webpages within app. from my knowledge and every ios air webView reference I have found online I have coded everything correctly. Runs beautifully on android.
apple app review says every tab and/or button launches mobile Safari.?
I don't see how this is possible because they even said my button that only has gotoAndPlay(2); apparently that navigates to Safari also. ?
here's the code I used for webView:
QMBTN.addEventListener(MouseEvent.CLICK, QMB);
function QMB(event:MouseEvent):void
{
webView.viewPort = new Rectangle( 0, 135, stage.stageWidth, 600 );
webView.stage = this.stage;
webView.loadURL( "http://mywebpageeurl.com.au" );
whiteBOX.gotoAndStop(2);
}
and this is the code for my internal frame nav.
Menu_BTN2.addEventListener(MouseEvent.CLICK, GoMenuSRC);
function GoMenuSRC(event:MouseEvent):void
{
webView.stage = null;
whiteBOX.gotoAndStop(1);
}
Am I missing something or ????
The only other thing I could think could be the culprit might be my error handler to handle errors when I click tel: or mailto: links on my webpages.
The code for the tel: / mailto: error handling.
// Error handle
var openLinksInDefaultBrowser = false;
//Check tel: func
function cdCTfunc():void
{
var NEWtelLNK = webView.location.substr(0,4);
if (NEWtelLNK=='tel:')
{
openLinksInDefaultBrowser = true;
}else{openLinksInDefaultBrowser = false;}
}
webView.addEventListener(LocationChangeEvent.LOCATION_CHANGING, function (ev:LocationChangeEvent):void
{
cdCTfunc();
if(openLinksInDefaultBrowser == false)
{
ev.preventDefault();
webView.loadURL(ev.location); //'ev.url' changed to 'ev.location'started with prerelease build - [07/20/10]
}
if (openLinksInDefaultBrowser == true)
{
trace('page loaded in default browser');
var phStr:String=ev.location;
var callPH:URLRequest= new URLRequest(phStr);
navigateToURL(callPH);
}
});
webView.addEventListener(LocationChangeEvent.LOCATION_CHANGE, function (ev:LocationChangeEvent):void
{
if (webView.location.indexOf('authentication_complete') != -1)
{
trace('auth token is: ' + webView.location.substr(webView.location.indexOf('token=') + 6));
}
trace('the new location is: ' + webView.location);
trace(webView.location.substr(0,4));
});
webView.addEventListener('complete', function(ev:Event):void
{
trace('complete event');
});
webView.addEventListener('error', function(ev:ErrorEvent):void
{
var phStr:String=webView.location;
var callPH:URLRequest= new URLRequest(phStr);
navigateToURL(callPH);
webView.isHistoryBackEnabled;
webView.historyBack();
trace('SOME Bloody Error Loading The Page: ' + ev.text);
trace(openLinksInDefaultBrowser);
});
but I still don't see how this could cause a gotoAndStop(); to launch safari.
I am absolutely stumped.
Please Help?
Thank you in advance.
Before submitting your app for review you should run it through Testflight.
This allows you to test an 'AppStore' build of your binary so you will see exactly what the reviewer will see.
http://www.yeahbutisitflash.com/?p=7608

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

Phonegap: BarcodeScanner & Childbrowser plugins

I'm facing a problem using this 2 PhoneGap plugins: "BarcodeScanner" & "ChildBrowser" (inside an iOS app, with XCode 4 & PhoneGap 2.0).
I've a button "Scan" on my app UI. When the user clic on this button, the barcode scanner is launched.
So, in the Success function of the barcode scanner callback, I need to open the recovered URL from the scan in a new Childbrowser window (inner the app).
But the new Childbrowser window is never been opened, while the console displays "Opening Url : http://fr.wikipedia.org/" (for example).
Here is my JS part of code:
$("#btnStartScan").click(function() {
var scanBarcode = window.plugins.barcodeScanner.scan(
function(result) {
if (!result.cancelled){
openUrl(result.text);
}
},
function(error) {
navigator.notification.alert("scanning failed: " + error);
});
});
function openUrl(url)
{
try {
var root = this;
var cb = window.plugins.childBrowser;
if(cb != null) {
cb.showWebPage(url);
}
else{
alert("childbrowser is null");
}
}
catch (err) {
alert(err);
}
}
And all works fine if I call my openURL() function inside a Confirm alert callback for example, like this:
if (!result.cancelled){
navigator.notification.confirm("Confirm?",
function (b) {
if (b === 1) {
openUrl(result.text);
}
},
'Test',
'Yes, No');
}
But I need to launch the ChildBrowser window directly after a scan, without any confirm alert etc.
Does anybody know how to solve this please?
I also have this same problem.
Solve it by set timeout.
var scanBarcode = window.plugins.barcodeScanner.scan(
function(result) {
if (!result.cancelled){
setTimeout(function(){ openUrl(result.text); },500);
}
},
function(error) {
navigator.notification.alert("scanning failed: " + error);
});
I'm running into the exact same problem.
My application also has another mechanism to show a webpage besides the barcode reader and when I do that action I can see that the barcode-related page HAD loaded, but it never was shown.
In ChildBrowserViewController.m, I'm looking at the last line of loadURL() which is webView.hidden = NO; and I'm thinking that the child browser is set visible after we barcode but something about the barcode reader window caused the child browser to get set to the wrong z-order, but I'm not familiar enough with the sdk to know how to test that or try to bring it to the front.
Hope this helps target a potential area.

Resources