Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IOS Bluetooth not discovering peripheral services. (sometimes!)

Sometimes, my app will connect to the peripheral device (i.e. "didConnectPeripheral" is called) but it will not discover available services ("didDiscoverServices" is not called). Also when this happens the peripheral (an Adafruit Bluefruit based on the nRF8001) will say its not connected! This only happens about 1/5 of the times the app is launched.

The blocks of code below are always executed:

func centralManager(central: CBCentralManager!, didDiscoverPeripheral peripheral: CBPeripheral!, advertisementData: [NSObject : AnyObject]!, RSSI: NSNumber!) {
     //Connect to the peripheral if its a UART
    if(peripheral.name == "UART") {
        currentPeripheral = peripheral
        currentPeripheral.delegate = self
        central.connectPeripheral(currentPeripheral, options: nil) 
    }
}


 func centralManager(central: CBCentralManager!, didConnectPeripheral peripheral: CBPeripheral!) {
    println()
    println("Connected to: \(peripheral.name)")
    peripheral.discoverServices(nil)
    connectionStatus = .Connected
    central.stopScan()
    println("***Stopped scanning***")
}

Any idea why "didDiscoverServices" is not called?

(I am running the app on an IPod touch 5th gen)

like image 560
Faris Avatar asked Jan 26 '26 04:01

Faris


1 Answers

According to the CoreBluetooth programming guide, you should do this:

Before you begin interacting with the peripheral, you should set the peripheral’s delegate to ensure that it receives the appropriate callbacks, like this:

peripheral.delegate = self;

Therefore, your didConnectPeripheral function should look something like this:

func centralManager(central: CBCentralManager!, didConnectPeripheral peripheral: CBPeripheral!) {
        NSLog("peripheral connected")
        peripheral.delegate = self
        peripheral.discoverServices(nil)

    }
like image 112
Jon Avatar answered Jan 27 '26 19:01

Jon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!