F_79
F_79

Reputation: 133

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)

Upvotes: 3

Views: 3274

Answers (1)

Jon
Jon

Reputation: 7918

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)

    }

Upvotes: 4

Related Questions