iOS - CoreBluetooth didDiscoverPeripheral not bein

2019-02-15 15:43发布

问题:

I have made a very simple iOS app in Xcode 6 to try out CoreBluetooth and communicate to my Polar H6 heart rate monitor. For some reason the didDiscoverPeripheral method is not being called.

I have found the following similar questions on StackOverflow but thy are either a bit different or do not really answer it for me:

  • corebluetooth-diddiscoverperipheral-not-being-called-in-swift
  • not-working-call-to-centralmanager-diddiscoverperipheral-advertisementdata
  • diddiscoverperipheral-delegate-method-is-not-called

My code in viewDidLoad:

NSArray *services = @[[CBUUID UUIDWithString:HRM_HEART_RATE_SERVICE_UUID]];
CBCentralManager *centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
[centralManager scanForPeripheralsWithServices:services options:nil];
self.centralManager = centralManager;

Method centralManagerDidUpdateState is being called and it tells me state is equal to CBCentralManagerStatePoweredOn. The didDiscoverPeripheral method is never called, not even when I pass nil into the scanForPeripheralsWithServices method.

Within the app store I have downloaded d an app called LightBlue. Its a very simple app to test any device which uses Bluetooth 4.0 LowEnergy. It scans for peripherals and shows detailed info about the devices and its services. The LightBlue app does see my HeartRate monitor, while my own little app does not..

Does anybody have any tips or clues how to go forward with this?

(I am using Xcode 6 and and iPhone 6 with iOS 8)

回答1:

I am using Swift, and it looks like the Bluetooth queue needs to be using the main queue

myCentralManager = CBCentralManager(delegate: self, queue: dispatch_get_main_queue())

Here it is in objective C

myCentralManager = [[CBCentralManager alloc] 
    initWithDelegate:self queue:dispatch_get_main_queue()];