2

I need to connect with a BLE device and then handle data as per sent via different button in it.
For that I wrote following code.

import CoreBluetooth
class HomeViewController: UIViewController,CBPeripheralDelegate,CBCentralManagerDelegate 
{
    var centralManager : CBCentralManager!
    var peri : CBPeripheral!
    override func viewDidLoad()
    {
        super.viewDidLoad()
        centralManager = CBCentralManager(delegate: self, queue: nil)
    }
    func centralManagerDidUpdateState(central: CBCentralManager) {
        if central.state == .Unknown
        {
            print("Unknown")
        }
        else if central.state == .Unsupported
        {
            print("Unsupported")
        }
        else if central.state == .Unauthorized
        {
            print("Unauthorized")
        }
        else if central.state == .Resetting
        {
            print("Resetting")
        }
        else if central.state == .PoweredOn
        {
            print("Powered On")
            startScan()
        }
        else if central.state == .PoweredOff
        {
            print("Powered Off")
        }
    }
    func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) {
        print("Discovered: \(peripheral.name) at \(RSSI)")
        print("AdvertisementData:\(advertisementData)")

        if peri != peripheral
        {
            peri = peripheral
            centralManager.connectPeripheral(peripheral, options: nil)
        }
    }
    func centralManager(central: CBCentralManager, didFailToConnectPeripheral peripheral: CBPeripheral, error: NSError?) {
        print("Failed to connect \(peripheral) cause of \(error)")
    }

    func centralManager(central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) {
        print("connected to \(peripheral)")
//        centralManager.stopScan()
        print("Available services:\(peripheral.services)")
    }
    func peripheral(peripheral: CBPeripheral, didDiscoverIncludedServicesForService service: CBService, error: NSError?) {
        print("Services\(service) and error\(error)")
    }
    func peripheral(peripheral: CBPeripheral, didDiscoverServices error: NSError?) {
        print("Services and error\(error)")
    }
    func startScan(){
        print("Scanning...")
        centralManager.scanForPeripheralsWithServices(nil, options: nil)
    }
}

And here is my Log for this code.

Powered On
Scanning...
Discovered: Optional("**** BLE") at 127
AdvertisementData:["kCBAdvDataIsConnectable": 1, "kCBAdvDataServiceUUIDs": (
    1802
)]
connected to <CBPeripheral: 0x12756d910, identifier = 6197****-EB0A-F1E8-BEF4-1AFAC629C5BC, name = **** BLE, state = connected>
Available services:nil

This is output is generated when one button is clicked from BLE device. But I am unable to receive or read data when another button is clicked.
Android developer of same app has integrated with both button.
So there is no any problem in device.
Can anyone help me to guide where I'm going wrong in this code??

3 Answers 3

7

Pandafox's answer is perfect just one thing is missing from it.
Which is setting delegate of peripheral.

Here is the complete code to discover peripheral, connect to it and discover its services and characteristics.

1.Connect peripheral

func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) {
    print("Discovered: \(peripheral.name) at \(RSSI)")
    print("AdvertisementData:\(advertisementData)")

    if peri != peripheral
    {
        peri = peripheral
        peri.delegate = self
        centralManager.connectPeripheral(peri, options: nil)
    }
}
  1. Connection failure or success

    func centralManager(central: CBCentralManager, didFailToConnectPeripheral peripheral: CBPeripheral, error: NSError?) {
        print("Failed to connect \(peripheral) cause of \(error)")
    }
    
    func centralManager(central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) {
        print("connected to \(peripheral)")
    //        centralManager.stopScan()
        peripheral.discoverServices(nil)
    }
    

3.DiscoverServices

func peripheral(peripheral: CBPeripheral, didDiscoverServices error: NSError?) {
        print("Services:\(peripheral.services) and error\(error)")
        if let services = peripheral.services {
            for service in services {
                peripheral.discoverCharacteristics(nil, forService: service)
            }
        }
    }
  1. Discover Characteristics and set notification

    func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError?)
        {
            print("peripheral:\(peripheral) and service:\(service)")
            for characteristic in service.characteristics!
            {
                peripheral.setNotifyValue(true, forCharacteristic: characteristic)
            }
        }
    
  2. Handle notification for update value of characteristics

    func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?)
        {
            print("characteristic changed:\(characteristic)")
        }
    
1
  • Just caught that and fixed my answer. Oh well.
    – Pandafox
    Jan 19, 2016 at 9:11
3

You also have to discover the services and characteristics after connecting to the device.

For example, in your "didConnectPeripheral" method, you will have to do something like:

 func centralManager(central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) {
    print("connected to \(peripheral)")
    peripheral.delegate = self
    peripheral.discoverServices(nil)
    print("Discovering services!")
}

And then:

func peripheral(peripheral: CBPeripheral, didDiscoverServices error: NSError?) {
    print("Discovered services: \(peripheral.services), Error\(error)")
    if let services = peripheral.services {
        for service in services {
            peripheral.discoverCharacteristics(nil, forService: service)
        }
    }
}

And then you have to handle each characteristic:

 func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError)

You must remember to store each characteristic manually, as they will be deallocated if you don't.

In order to receive streaming data (notifications) you will have to enable notify for each characteristic.

peripheral.setNotifyValue(true, forCharacteristic: characteristic)

You also have to implement:

 func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError)

Order to handle the incoming values.

As you can see, there's quite a bit of boiler plate code required to get started.

3
  • updated code as per your suggestion, But still not any update on logScreen. Still not getting any services from peripheral. Jan 19, 2016 at 5:15
  • You must also remember to set the peripheral delegate. I updated the "didConnectPeripheral" method and added "peripheral.delegate = self". See if that will get you any further.
    – Pandafox
    Jan 19, 2016 at 8:15
  • func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError) This method not call . please help me . Nov 1, 2018 at 13:45
1

After connecting to the peripheral you have to call discoverServices on the peripheral with the UUID of the services you want to discover, you then have to discover the characteristics of the service. If you want updates when a button is clicked, you will have to turn notifications on for the characteristic corresponding to that button

I would highly recommend this link from apple for follow up reading if you still need help. It describes what you need to do step by step in a better fashion than I could ever describe here.

Apple BLE Guide

1
  • Thanks for answering, I missed to call discoverServices on peripheral. But after updating still not getting any updates on logScreen Jan 19, 2016 at 5:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.