SWIFT – BLE communications

The following code is for Swift 3 (XCode 8 Beta 6). It’s an example using the standard UUIDs for serial ports like the ones on some commercial modules. So the declarations for the service and characteristics should look like this:

private let UuidSerialService = "6E400001-B5A3-F393-E0A9-E50E24DCCA9E"
private let UuidTx =            "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"
private let UuidRx =            "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"

And then your delegate’s method for the didDiscoverCharacteristic can be something like this:

public func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?)
{
    if let characteristics = service.characteristics {
        for characteristic in characteristics {
            // Tx:
            if characteristic.uuid == CBUUID(string: UuidTx) {
                print("Tx char found: \(characteristic.uuid)")
                txCharacteristic = characteristic
            }

            // Rx:
            if characteristic.uuid == CBUUID(string: UuidRx) {
                rxCharacteristic = characteristic
                if let rxCharacteristic = rxCharacteristic {
                    print("Rx char found: \(characteristic.uuid)")
                    serialPortPeripheral?.setNotifyValue(true, for: rxCharacteristic)
                }
            }
        }
    }
}

For writing to the Tx, something like the following works, where value is an [UInt8]:

let data = NSData(bytes: value, length: value.count)
serialPortPeripheral?.writeValue(data as Data, for: txCharacteristic, type: CBCharacteristicWriteType.withResponse)

Reading?

public func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
    let rxData = characteristic.value
    if let rxData = rxData {
        let numberOfBytes = rxData.count
        var rxByteArray = [UInt8](repeating: 0, count: numberOfBytes)
        (rxData as NSData).getBytes(&rxByteArray, length: numberOfBytes)
        print(rxByteArray)
    }
}

Finally, if you don’t know or you are not sure about the services and characteristics of your BLE device, you can look for a free iOS app called “LightBlue”. It will discover a device and if you connect to it, it will list all services and characteristics. Just be aware that obvoiusly your app will not be able to access the BLE hardware while LightBlue is connected to your device.

Leave a Comment