Xamarin Forms Maps - showing current location on iOS - c#

In Xamarin Forms, does the IsShowingUser property of Xamarin.Forms.Maps work for iOS?
I can get every aspect of my map to work on both Android and iOS, but the current location 'blue dot' does not show on iOS.
I'm setting this in shared code in the PCL project, just after successfully asking for permission to use location.
var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Location);
if (status != PermissionStatus.Granted)
{
var results = await CrossPermissions.Current.RequestPermissionsAsync(new[] { Permission.Location });
status = results[Permission.Location];
}
if (status == PermissionStatus.Granted)
{
MyMap.IsShowingUser = true;
}
thanks

I can get every aspect of my map to work on both Android and iOS, but the current location 'blue dot' does not show on iOS.
It is because the map doesn't locate the current user location at that time, you can use Xam.Plugin.Geolocator to get your current location, and move the map to it.
var locator = CrossGeolocator.Current;
var position = await locator.GetPositionAsync(TimeSpan.FromSeconds(10));
map.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(position.Latitude, position.Longitude),
Distance.FromMiles(1)));

Related

How to enable screen capture (video) using AppRecordingManager in a WPF project?

I'm trying to capture a video of my application using UWP APIs, specifically the Windows.Media.AppRecording namespace. When I try to execute the code I get a CanRecord flag as false, and the reason given by the Details property is that "something" is disabled by the user.
How can I enable the screen capture? Do I need a specific configuration file, or manifest?
My application is as simple as it get: Just a WPF in .NET 4.7.2, consisting in a button to start recording and a button to stop recording.
Here is the method:
public async Task StartRecordingAsync(string fileName)
{
AppRecordingManager manager = AppRecordingManager.GetDefault();
var status = manager.GetStatus();
if (status.CanRecord || status.CanRecordTimeSpan)
{
var myVideo = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Videos);
StorageFolder projectFolder = await myVideo.SaveFolder.CreateFolderAsync("DataFolder", CreationCollisionOption.OpenIfExists);
var audio = await projectFolder.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName);
var result = await manager.StartRecordingToFileAsync(audio).AsTask<AppRecordingResult>(CTS.Token);
if (result.Succeeded)
{
IsRecording = true;
}
else
{
IsRecording = false;
}
}
}
And here are the Details given by the status variable:
status.Details
The IsDisbaledByUser property of the AppRecordingStatusDetails is false when the user does not allow apps to record.
True if app recording has been disabled by the user; otherwise, false.
To allow apps to record, you need to enable Game Bar from Windows Settings:
Settings -> Gaming -> Record game clips, screenshots, and broadcast using Game bar

Playing in-built webcam feed in a UWP app stopped working after?

I'm trying to play the built-in webcam feed in a MediaElement within a UWP app. It works fine for a few users but there is no feed played for most and I'm lost on what could be the issue.
Some observations when the webcam feed doesn't play:
The code executes without any exceptions
The dialog that requests user permission to access the camera is shown
The LED indicating the webcam is in use turns on soon as it is executed, but there is no feed.
Skype and Camera apps work fine.
The app was working as expected until a week back. A few things that changed in the mean time that could have had an impact are
Installed Kaspersky
A bunch of windows updates
Uninstalled VS2017 professional edition & VS2019 Community edition and installed VS2019 Professional Edition
Some additional information that might be needed to narrow down the reason.
Webcam is enabled in the Package manifest of the app
App Target version: 18362
App Min version: 18362
Windows OS Version : 18362
Any help on this would be highly appreciated. Thanks much in advance!
Here is the piece of code used to play the webcam feed where VideoStreamer is a MediaElement.
private async Task PlayLiveVideo()
{
var allGroups = await MediaFrameSourceGroup.FindAllAsync();
var eligibleGroups = allGroups.Select(g => new
{
Group = g,
// For each source kind, find the source which offers that kind of media frame,
// or null if there is no such source.
SourceInfos = new MediaFrameSourceInfo[]
{
g.SourceInfos.FirstOrDefault(info => info.DeviceInformation?.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Front
&& info.SourceKind == MediaFrameSourceKind.Color),
g.SourceInfos.FirstOrDefault(info => info.DeviceInformation?.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back
&& info.SourceKind == MediaFrameSourceKind.Color)
}
}).Where(g => g.SourceInfos.Any(info => info != null)).ToList();
if (eligibleGroups.Count == 0)
{
System.Diagnostics.Debug.WriteLine("No source group with front and back-facing camera found.");
return;
}
var selectedGroupIndex = 0; // Select the first eligible group
MediaFrameSourceGroup selectedGroup = eligibleGroups[selectedGroupIndex].Group;
MediaFrameSourceInfo frontSourceInfo = selectedGroup.SourceInfos[0];
MediaCapture mediaCapture = new MediaCapture();
MediaCaptureInitializationSettings settings = new MediaCaptureInitializationSettings()
{
SourceGroup = selectedGroup,
SharingMode = MediaCaptureSharingMode.ExclusiveControl,
MemoryPreference = MediaCaptureMemoryPreference.Cpu,
StreamingCaptureMode = StreamingCaptureMode.Video,
};
try
{
await mediaCapture.InitializeAsync(settings);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("MediaCapture initialization failed: " + ex.Message);
return;
}
var frameMediaSource1 = MediaSource.CreateFromMediaFrameSource(mediaCapture.FrameSources[frontSourceInfo.Id]);
VideoStreamer.SetPlaybackSource(frameMediaSource1);
VideoStreamer.Play();
}
As mentioned by Faywang-MSFT here , it worked after marking the application as trusted in Kaspersky.

MobileBardodeScanner fails to scan QRCode untill restarted after giving Camera Permissions

I'm trying to scan a QR Code from my Xamarin.Forms application but the QR Code isn't getting detected until i restart the scanner.
I'm using ZXing.Net.Mobile.Forms. Once the ScannerPage has been pushed on the navigation stack it requests the camera permissions. After fulfilling the request it has access to the camera but isn't scanning the QR Code. I tried changing the permission handler since it works after restarting the scanner after granting the permission, but that didn't work.
private async void createScanPageAsync()
{
#if __ANDROID__
// Initialize the scanner first so it can track the current context
MobileBarcodeScanner.Initialize (Application);
#endif
var options = new MobileBarcodeScanningOptions()
{
TryHarder = true,
};
var scanPage = new ZXingScannerPage()
{
Title = AppResources.scanPageTitle,
DefaultOverlayTopText = AppResources.scanPageTitle,
DefaultOverlayShowFlashButton = true
};
await Navigation.PushAsync(scanPage);
scanPage.OnScanResult += (scanResult) =>
{
scanPage.IsScanning = false;
Vibration.Vibrate();
QRCode scans = JsonConvert.DeserializeObject<QRCode>(scanResult.Text);
AppPreferences.Network.Ip = scans.ip;
AppPreferences.Network.Port = scans.port;
Device.BeginInvokeOnMainThread(async () =>
{
await Navigation.PopAsync();
});
};
}
}
The expected outcome would be a successful scan on the first try, but i only get a successful scan after granting permissions and then reopening the scanner page.
For me the Xamarin.Essentials did the trick. It has a permission plugin that can help you ask for permission and after that, you can then launch the scanner without problem

DeviceConnectionChangeTrigger - Value does not fall within the expected range

I'm developing an UWP app for Desktop and Mobile. I'd like using DeviceConnectionChangeTrigger to identify when my BT device is in range, but when i try using it, I cannot register background task cause it keeps return System.ArgumentException "Value does not fall within the expected range." when executing "Register" method of BackgroundTaskBuilder.
code is very simple
var current = BackgroundExecutionManager.GetAccessStatus();
if (current == BackgroundAccessStatus.Unspecified || current == BackgroundAccessStatus.Denied)
{
var result = await BackgroundExecutionManager.RequestAccessAsync();
if (result == BackgroundAccessStatus.Denied || result == BackgroundAccessStatus.Unspecified)
throw new Exception("You cannot register Access");
}
//I tested it with BT and BTLE device but no luck
//var devices = await DeviceInformation.FindAllAsync(BluetoothLEDevice.GetDeviceSelector());
var devices = await DeviceInformation.FindAllAsync(BluetoothDevice.GetDeviceSelector());
var device = devices.FirstOrDefault();
if (device == null) throw new Exception("Device not found");
var trigger = await DeviceConnectionChangeTrigger.FromIdAsync(device.Id);
//trigger.MaintainConnection = true;
var builder = new BackgroundTaskBuilder
{
Name = "BluetoothConnectionWatcher",
TaskEntryPoint = typeof(BluetoothConnectionWatcherTask).FullName
};
builder.SetTrigger(trigger);
//error on next line!
var r = builder.Register();
My project has Bluetooth capabilities and one background task registered with Bluetooth property flagged.
All Bluetooth functionalities work well and I can communicate with devices without problem.
I tried several BT and BTLE device and for all of them seems I have the same problem.
I tried on Desktop and Mobile version of Windows 10 (both last fast insider build). Same problem.
The device.Id returned by code is similar to "Bluetooth#Bluetooth00:1a:7d:da:71:0a-fc:58:fa:4c:17:0a" for every BT device i tried (of course 2nd MAC address change based on device...)
Any advice?
Thanks in advance
As far as I know, with BLE you should use the Triggers designed for it. Thus if it is characteristics change you would want to get knowledge about, then you should use GattCharacteristicNotificationTrigger, and example on using it can be found from my blog.
Then if it just BLE device availability, and you can detect yours via scanrecord data, then do use the BluetoothLEAdvertisementWatcherTrigger instead. My Friend Juhana has example fro this in his blog.

Control Widows Media Device Flash Light

I am trying to create a simple application which will have the functionality to switch on and off the flash light in a Windows Media Device.
I have initialized the camera as following:
var devices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
var rearCamera = devices.FirstOrDefault(item => item.EnclosureLocation != null &&
item.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back);
if (rearCamera != null)
{
DeviceName.Content = rearCamera.Name;
FlashButton.Visibility = System.Windows.Visibility.Visible;
mediaCapture = new MediaCapture();
await mediaCapture.InitializeAsync(new MediaCaptureInitializationSettings
{
VideoDeviceId = rearCamera.Id
});
LowLagPhotoCapture lowLagCaptureMgr = null;
// Image properties
ImageEncodingProperties imgFormat = ImageEncodingProperties.CreateJpeg();
// Create LowLagPhotoCapture object
lowLagCaptureMgr = await mediaCapture.PrepareLowLagPhotoCaptureAsync(imgFormat);
}
And to switch on the flash I have written the following code:
var MyVideoDeviceController = mediaCapture.VideoDeviceController;
var MyTorch = MyVideoDeviceController.TorchControl;
var MyFlash = MyVideoDeviceController.FlashControl;
if (MyTorch.Supported)
{
MyTorch.PowerPercent = 100;
MyTorch.Enabled = true;
}
else
{
if (MyFlash.Supported)
{
MyFlash.PowerPercent = 100;
MyFlash.Enabled = true;
}
else
{
MessageBox.Show("No Flash and Torch Support", "Flash and Torch");
}
}
But seems both TorchControl and FlashControl are not supported in the code. I am not sure if am using the right APIs too. I am trying to run this on a Motion F5m - Tablet PC
Thanks in advance
The TorchControl is used for constant video light, so if you're taking a photograph, it's not the most appropriate control to use. One reason is that on many devices, video light will be dimmer than a photo flash, but especially because on some devices, the torch will only turn on while a video recording is in progress. Depending on the capabilities of the device, this may interfere with the ability to take photos.
You have the right idea setting MyFlash.Enabled = true, but just to be safe, I would also set MyFlash.Auto = false, so that the flash will fire each time, and not only when it's dark.
The CameraManualControls sample on the Microsoft GitHub repository shows you how to use the Flash and Torch controls, and many more. It targets Windows 10, though, so if you're on 8.1 you'll have to adapt the code or upgrade your tablet.
Now, all of the above is assuming that the device you're running your app on has flash support in the first place. When you say that the controls are not supported, that means that the camera driver on the device is not advertising the capability to Windows. I assume that the built-in Microsoft Camera app doesn't allow you to use the flash either?
I see the manufacturer of your tablet lists an "Illuminator Light" on their camera specs list, but there is a chance that the only way to control it is through their proprietary application. In that case you'd have to reach out to them for support.

Categories

Resources