iOS Configure Beacons with CoreBluetooth

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Introduction

Hot to read and write data to a bluetooth low energy device.

Remarks

Some important points

  • No capabilities are needed.
  • iPhone store bytes in Little Endian format, so check if bluetooth accessory use Little Endian too. Example:
    • intel CPU usually use little endian.
    • The ARM architecture was little-endian before version 3 when it became big-endian.
  • After a single or batch operation the connection will be lost, so you have to reconnect before continue.

Scan for SERVICE UUID

func SearchBLE(){
    cb_manager.scanForPeripherals(withServices:[service_uuid], options: nil)
    StopSearchBLE()
}

How to discover SERVICE UUID without documentation

func centralManager(_ central: CBCentralManager, didConnect peripheral:             
CBPeripheral) {
        peripheral.delegate = self
        peripheral.discoverServices(nil)
}

func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
    for service in peripheral.services! {
        print("Service: \(service)\n error: \(error)")
    }
}
  • discoverServices(nil) - NIL means that all services will be returned, which is not a good option.( READ Remarks 3)
  • If you haven't found the SERVICE UUID run your code and looking for in console enter image description here
  • I found have 3 services: Battery, Device information (Firmware) and FFF0
  • This uuid service isn't a standard one, a list with standards can find here
  • FFF0 is the SERVICE UUID in this case

Convert data to UInt16 and contrary

Add this extensions to your class

protocol DataConvertible {
    init?(data: Data)
    var data: Data { get }
}

extension DataConvertible {

    init?(data: Data) {
        guard data.count == MemoryLayout<Self>.size else { return nil }
        self = data.withUnsafeBytes { $0.pointee }
    }

    var data: Data {
        var value = self
        return Data(buffer: UnsafeBufferPointer(start: &value, count: 1))
    }
}
extension UInt16 : DataConvertible {
    init?(data: Data) {
        guard data.count == MemoryLayout<UInt16>.size else { return nil }
        self = data.withUnsafeBytes { $0.pointee }
    }
    var data: Data {
        var value = CFSwapInt16HostToBig(self)
        return Data(buffer: UnsafeBufferPointer(start: &value, count: 1))
    }
}


Got any iOS Question?