Can't seem to get core bluetooth to work

2019-09-08 17:52发布

I can't seem to get core bluetooth working on my iPad.

ViewController.h

@interface ViewController : UIViewController <CBCentralManagerDelegate, CBPeripheralDelegate>
{
    CBCentralManager *manager;
}
@end

ViewController.m

#import "ViewController.h"

@interface ViewController ()

@property (strong, nonatomic) IBOutlet UITextView *textField;

@end

@implementation ViewController

@synthesize textField;

- (void)viewDidLoad
{
    [super viewDidLoad];
    manager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)action:(id)sender {
    textField.text = @"";

    if (manager.state == CBCentralManagerStatePoweredOn) {
        textField.text = @"Scanning...";
        NSLog(@"scanning");
        [manager scanForPeripheralsWithServices:nil options:nil];
    } else {
        textField.text = @"Error";
    }
}

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI {
    NSLog(@"2");
    textField.text = [NSString stringWithFormat:@"%@%@\n", textField.text, peripheral.name];
}

- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
    NSLog(@"d");
}

@end

2 never gets logged and devices are never detected. I made sure that bluetooth is enabled in my settings.

What's wrong with the code? Could it just be that no applicable devices are discovered? I can discover my iMac just fine in bluetooth settings.

Also, can Core Bluetooth (running on a device with bluetooth LE) detect non bluetooth LE devices? Such as a wireless headset?

1条回答
淡お忘
2楼-- · 2019-09-08 18:16

Core Bluetooth only works with Bluetooth Low Energy and the code you have will only discover peripheral BLE devices, like BLE tags, heart rate monitors, sensors or iOS 6 devices in peripheral mode.

So no, you can't detect your iMac (OS X still has no peripheral mode via Core Bluetooth) or wireless headset this way. Or any other way with official SDK.

查看更多
登录 后发表回答