crazydev
crazydev

Reputation: 575

Check Bluetooth status in Xamarin Forms on iOS

I have created a xamarin forms application. I want to check if the status of the bluetooth in iOS. I have used the below code, but the if (state == CBCentralManagerState.PoweredOn) is returning me Unknown. It is not providing the actual status of bluetooth state. Could somebody please help me to figure out what is wrong ? Thanks.

The reference of this method is here : https://developer.xamarin.com/api/type/MonoMac.CoreBluetooth.CBCentralManagerState/

   private CBCentralManagerState state;

    public bool CheckBluetoothStatus()
    {
        bool status;
        if (state == CBCentralManagerState.PoweredOn)
        {
            status=  true;
        }
        else
        {
            status =  false;
        }
        return status;   

    }

Upvotes: 4

Views: 3077

Answers (2)

Madhav Shenoy
Madhav Shenoy

Reputation: 756

As described here in apple documentation, you need to initialise CBCentralManager before you can actually use it.

If you look at Xamarin Documentation for CBCentralManager, they provide you a list of all constructors it takes. Implement the 2nd one from the bottom

CBCentralManager(CBCentralManagerDelegate, DispatchQueue, CBCentralInitOptions)

But before you implement this, you need to implement the CBCentralManagerDelegate. It could be as simple as this

public class CbCentralDelegate : CBCentralManagerDelegate
{
    public override void UpdatedState(CBCentralManager central)
    {
        if(central.State == CBCentralManagerState.PoweredOn)
        {
            System.Console.WriteLine("Powered On");
        }
    }
}

Now that you have implemented the delegate, you should be able to fetch the state of the bluetooth from the CBCentralManager like this

var bluetoothManager = new CBCentralManager(new CbCentralDelegate(),DispatchQueue.DefaultGlobalQueue,
                                                        new CBCentralInitOptions{ShowPowerAlert = true});

return bluetoothManager.State == CBCentralManagerState.PoweredOn;

I know its been a while since this was asked, but hopefully this will help you.(Or anyone else)

Upvotes: 4

Jesse Jiang
Jesse Jiang

Reputation: 965

You should subscript the UpdatedState event in CBCentralManager

_mgr = new CBCentralManager();
_mgr.UpdatedState += CBCentralManager_UpdatedState;
void CBCentralManager_UpdatedState(object sender, EventArgs e){
    switch (_mgr.State)
}

Upvotes: 0

Related Questions