Xamarin iOS ZXing Barcode read using front camera issue - ios

I am trying to implement a barcode scanning app using Xamarin and ZXing. Unfortunately scanning is not working well with front camera on iPhone and iPad. Any suggestions or help appreciated

Your InitializeScanner method can do scanner initialization as below and invokes start scanning, in my case I wanted to support barcode and QR code both. You can remove scanning option QRCode if you do not want to support it.
The callback mentioned while initialization is getting called back when scanner recognizes the code and returns unique string.
The scanner option has property UseFrontCameraIfAvailable
var mobileBarcodeScanningOptions= new ZXing.Mobile.MobileBarcodeScanningOptions();
mobileBarcodeScanningOptions.UseFrontCameraIfAvailable = true;
mobileBarcodeScanningOptions.PossibleFormats = new List<ZXing.BarcodeFormat>() {
ZXing.BarcodeFormat.CODE_128,
ZXing.BarcodeFormat.CODE_93,
ZXing.BarcodeFormat.CODE_39,
ZXing.BarcodeFormat.PDF_417,
ZXing.BarcodeFormat.QR_CODE
};
mobileBarcodeScanningOptions.AutoRotate = false;
mobileBarcodeScanningOptions.TryHarder = true;
mobileBarcodeScanningOptions.TryInverted = false;
var scanview = new ZXingScannerView(new CGRect(0, 0, View.Frame.Width, View.Frame.Height)) { }
scanview.AutoFocus();
//code to add your scanview in your main view
scanview.StartScanning(MyScanResultHandler, mobileBarcodeScanningOptions);
//After scanning code, scanner callbacks below method
private void MyScanResultHandler(Result obj)
{
if (obj != null)
{
//obj.Text gives you value of code in string which you can use further in your application
}
}

Related

Web Audio API not playing sound sample on device, but works in browser

I have an Ionic app that is a metronome. Using Web Audio API I have made everything work using the oscillator feature, but when switching to use a wav file no audio is playing on a real device (iPhone).
When testing in the browser using Ionic Serve (chrome) the audio plays fine.
Here is what I have:
function snare(e) {
var audioSource = 'assets/audio/snare1.wav';
var request = new XMLHttpRequest();
request.open('GET', audioSource, true);
request.responseType = 'arraybuffer';
// Decode asynchronously
request.onload = function() {
audioContext.decodeAudioData(request.response, function(theBuffer) {
buffer = theBuffer;
playSound(buffer);
});
}
request.send();
}
function playSound(buffer) {
var source = audioContext.createBufferSource();
source.buffer = buffer;
source.connect(audioContext.destination);
source.start(0);
}
The audio sample is in www/assets/audio.
Any ideas where this could be going wrong?
I believe iOS devices require a user-gesture of some sort to allow playing of audio.
It's July 2017, iOS 10.3.2 and we're still finding this issue on Safari on iPhones. Interestingly Safari on a MacBook is fine.
#Raymond Toy's general observation still appears to be true. But #padenot's approach (via https://gist.github.com/laziel/7aefabe99ee57b16081c) did not work for me in a situation where I wanted to play a sound in response to some external event/trigger.
Using the original poster's code, I've had some success with this
var buffer; // added to make it work with OP's code
// keep the original function snare()
function playSound() { // dropped the argument for simplicity.
var source = audioContext.createBufferSource();
source.buffer = buffer;
source.connect(audioContext.destination);
source.start(0);
}
function triggerSound() {
function playSoundIos(event) {
document.removeEventListener('touchstart', playSoundIos);
playSound();
}
if (/iPad|iPhone/.test(navigator.userAgent)) {
document.addEventListener('touchstart', playSoundIos);
}
else { // Android etc. or Safari, but not on iPhone
playSound();
}
}
Now calling triggerSound() will produce the sound immediately on Android and will produce the sound on iOS after the browser page has been touched.
Still not ideal, but better than no sound at all...
I had a similar issue in current iOS (15). I tried to play base64 encoded binary data which worked in all browsers, but not on iOS.
Finally reordering of the statements solved my issue:
let buffer = Uint8Array.from(atob(base64), c => c.charCodeAt(0));
let context = new AudioContext();
// these lines were within "play()" before
audioSource = context.createBufferSource();
audioSource.connect(context.destination);
audioSource.start(0);
// ---
context.decodeAudioData(buffer.buffer, play, (e) => {
console.warn("error decoding audio", e)
});
function play(audioBuffer) {
audioSource.buffer = audioBuffer;
}
Also see this commit in my project.
I assume that calling audioSource.start(0) within the play() method was somehow too late because it's within a callback after context.decodeAudioData() and therefore maybe "too far away" from a user interaction for the standards of iOS.

Is there a way to tell if a MIDI-Device is connected via USB on iOS?

I'm using CoreMIDI to receive messages from a MIDI-Keyboard via Camera Connection Kit on iOS-Devices. My App is about pitch recognition. I want the following functionality to be automatic:
By default use the microphone (already implemented), if a MIDI-Keyboard is connected use that instead.
It's could find out how to tell if it is a USB-Keyboard using the default driver. Just ask for the device called "USB-MIDI":
private func getUSBDeviceReference() -> MIDIDeviceRef? {
for index in 0..<MIDIGetNumberOfDevices() {
let device = MIDIGetDevice(index)
var name : Unmanaged<CFString>?
MIDIObjectGetStringProperty(device, kMIDIPropertyName, &name)
if name!.takeRetainedValue() as String == "USB-MIDI" {
return device
}
}
return nil
}
But unfortunately there are USB-Keyboards that use a custom driver. How can I tell if I'm looking at one of these? Standard Bluetooth- and Network-Devices seem to be always online. Even if Wifi and Bluetooth are turned of on the device (strange?).
I ended up using the USBLocationID. It worked with any device I tested so far and none of the users complained.But I don't expect many users to use the MIDI-Features of my app.
/// Filters all `MIDIDeviceRef`'s for USB-Devices
private func getUSBDeviceReferences() -> [MIDIDeviceRef] {
var devices = [MIDIDeviceRef]()
for index in 0..<MIDIGetNumberOfDevices() {
let device = MIDIGetDevice(index)
var list: Unmanaged<CFPropertyList>?
MIDIObjectGetProperties(device, &list, true)
if let list = list {
let dict = list.takeRetainedValue() as! NSDictionary
if dict["USBLocationID"] != nil {
devices.append(device)
}
}
}
return devices
}

Xamarin forms zxing ZXingScannerView on ios

I am writing a mobile app in xamarin forms and I have half the screen continuously scanning barcodes using ZXingScannerView. This works great in android however in ios it will not pick up any barcodes using ZXingScannerView. However ios does pick up barcodes using the full page ZXingScannerPage. In my example code below the method Scanner_OnScanResult is never getting hit. How can I get this to work in ios am i missing something?
ZXingScannerView scanner = new ZXingScannerView
{
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand,
AutomationId = "zxingScannerView",
IsScanning = true,
Options = new ZXing.Mobile.MobileBarcodeScanningOptions
{
UseFrontCameraIfAvailable = false,//update later to come from settings
PossibleFormats = new List<ZXing.BarcodeFormat>(),
TryHarder = true
}
};
ZXingDefaultOverlay overlay = new ZXingDefaultOverlay();
scanner.Options.PossibleFormats.Add(ZXing.BarcodeFormat.QR_CODE);.
scanner.OnScanResult += Scanner_OnScanResult;
private void Scanner_OnScanResult(ZXing.Result result)
{
DisplayAlert("Exit", "TEST", "Yes", "No");
}
I eventually got this working however i'm not sure if its a bug or just inconsistent design but in iOS IsAnalyzing must be set to true manually when working in a view

Preventing the camera to rotate in iPad app using MvvmCross PictureChooser

I'm using Xamarin with MvvmCross to create an iPad application. In this application I use the PictureChooser plugin to take a picture with the camera. This all occurs in the way that can be seen in the related youtube video.
The code to accomplish this is fairly simple and can be found below. However when testing this on the actual device, the camera might be rotated.
private readonly IMvxPictureChooserTask _pictureChooserTask;
public CameraViewModel(IMvxPictureChooserTask pictureChooserTask)
{
_pictureChooserTask = pictureChooserTask;
}
private IMvxPictureChooserTask PictureChooserTask { get { return _pictureChooserTask; } }
private void TakePicture()
{
PictureChooserTask.TakePicture(400, 95,
async (stream) =>
{
using (var memoryStream = new MemoryStream())
{
stream.CopyTo(memoryStream);
var imageBytes = memoryStream.ToArray();
if (imageBytes == null)
return;
filePath = ProcessImage(imageBytes, FileName);
}
},
() =>
{
/* no action - we don't do cancellation */
}
);
}
This will lead to unwanted behavior. The camera should remain steady and be prevented in rotating within the App. I have been trying some stuff out, like preventing the app from rotating in the override bool ShouldAutorotate method while in camera mode, but unfortunately without any results.
Is there any setting that I forgot to set on the PictureChooser, or is the override method the item where I should perform some magic?
Thanks in advance.
Answer to this question has been raised in the comments of the question by user3455363, many thanks for this! Eventually it seemed to be a bug in iOS 8. The iOS 8.1 upgrade fixed this issue in my App!

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