1 | initial version |
To scan beacons in the background using Plugin.BLE in Xamarin.Forms, you can use the following steps:
<key>UIBackgroundModes</key>
<array>
<string>bluetooth-central</string>
</array>
<key>NSBluetoothAlwaysUsageDescription</key>
<string>Your description here</string>
<key>NSBluetoothPeripheralUsageDescription</key>
<string>Your description here</string>
public override void PerformFetch(UIApplication application, Action<UIBackgroundFetchResult> completionHandler)
{
// Scanning code goes here.
completionHandler(UIBackgroundFetchResult.NewData);
}
public class BackgroundScanner
{
private IBluetoothLE ble;
private IAdapter adapter;
private CancellationTokenSource tokenSource;
public async Task StartScan()
{
try
{
tokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(500));
// Retrieve the BluetoothLE interface.
ble = CrossBluetoothLE.Current;
// Retrieve the adapter.
adapter = CrossBluetoothLE.Current.Adapter;
// Scan for devices.
adapter.DeviceDiscovered += Adapter_DeviceDiscovered;
await adapter.StartScanningForDevicesAsync(tokenSource.Token);
}
catch (Exception ex)
{
// Handle any exceptions here.
}
}
private void Adapter_DeviceDiscovered(object sender, DeviceEventArgs e)
{
// Handle the discovered devices here.
}
public async Task StopScan()
{
await adapter.StopScanningForDevicesAsync();
}
}
public override void PerformFetch(UIApplication application, Action<UIBackgroundFetchResult> completionHandler)
{
var scanner = new BackgroundScanner();
Task.Factory.StartNew(async () =>
{
await scanner.StartScan();
completionHandler(UIBackgroundFetchResult.NewData);
await scanner.StopScan();
}, TaskCreationOptions.LongRunning);
}
public static class MainClass
{
public static void Main(string[] args)
{
UIApplication.Main(args, null, "AppDelegate");
}
}
This will start scanning beacons in the background using Plugin.BLE in Xamarin.Forms.