xcode: 如何在条件操作中使用蓝牙状态

xcode: how do I use bluetooth status in a conditional operation

逻辑是这样的:

if (blueTooth is on){
    performSegueToPageA
}
else{
    performSegueToPageB
}

但我一辈子都不知道该怎么做。首先,这些过于复杂(就 Stack Overflow 而言,并不总是有效,具体取决于 iOS 版本或风向)CBCentralManager 废话。

其次,我如何调用和构造它以使其 return 成为 BOOL 值?

假设我只针对 iOS7+。

这是我目前得到的结果:

login.h:

@interface bla bla blah <AmongOtherThings, CBCentralManagerDelegate>
@property (nonatomic, strong) CBCentralManager* blueToothManager;

login.m:

#import <CoreBluetooth/CoreBluetooth.h>
- (void)viewDidLoad {
    [self detectBluetooth]
}

- (void)detectBluetooth
{
    if(!self.blueToothManager)
    {
        // Put on main queue so we can call UIAlertView from delegate callbacks.
        self.blueToothManager = [[[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()];
    }
    [self centralManagerDidUpdateState:self.blueToothManager]; // Show initial state
}

- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    NSString *stateString = nil;
    switch(_blueToothManager.state)
    {
        case CBCentralManagerStateResetting: stateString = @"The connection with the system service was momentarily lost, update imminent."; break;
        case CBCentralManagerStateUnsupported: stateString = @"The platform doesn't support Bluetooth Low Energy."; break;
        case CBCentralManagerStateUnauthorized: stateString = @"The app is not authorized to use Bluetooth Low Energy."; break;
        case CBCentralManagerStatePoweredOff: stateString = @"Bluetooth is currently powered off."; break;
        case CBCentralManagerStatePoweredOn: stateString = @"Bluetooth is currently powered on and available to use."; break;
        default: stateString = @"State unknown, update imminent."; break;
    }
    NSLog(@"%@", stateString);
}

供参考,在代码上,看here。值得注意的是,我不得不在 centralManagerDidUpdateState 中向 blueToothManager.state 添加下划线,因为没有它代码将无法构建。

照原样,它运行良好。现在,如何将其设为 return BOOL 值?

我认为这并不像用 void 代替 BOOL(我试过)那么简单。

谢谢。

在您的 centralManagerDidUpdateState 函数中,您可以简单地检查:

if (self.blueToothManager.state == CBCentralManagerStatePoweredOn)
{
        //Do something
}
else 
{
        //Do something else
}