I have a working code. Here I will give some fragments. In the first ViewController that matches CBCentralManagerDelegate, we have:
var cbc : CBCentralManager? = nil
override func viewDidLoad() {
super.viewDidLoad()
cbc = CBCentralManager(delegate: self, queue: nil)
}
the touch of a button starts scanning for peripherals
@IBAction func scan(_ sender: Any) {
cbc?.scanForPeripherals(withServices: nil, options: nil)
}
for each peripheral device the next delegate member is found, which will be called
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
NSLog("name=%@", peripheral.name ?? "unnamed")
}
, . ,
@IBAction func connect(_ sender: Any) {
cbc?.connect(selectedPeripheral!, options: nil)
}
:
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
performSegue(withIdentifier: "ConnectPeriph", sender: self)
}
ViewController, . ViewController CBPeripheralDelegate :
var periph : CBPeripheral!
var dataChar : CBCharacteristic?
let mchpPrivateService : CBUUID = CBUUID(string: "00035B03-58E6-07DD-021A-08123A000300")
let mchpDataPrivateChar : CBUUID = CBUUID(string: "00035B03-58E6-07DD-021A-08123A000301")
- , :
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
periph.delegate = self
periph.discoverServices(nil)
}
:
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
if let e = error {
NSLog("Error %@", e.localizedDescription)
}
else if let services = peripheral.services {
for s in services {
NSLog("Service=%@", s.uuid.uuidString)
if s.uuid.isEqual(mchpPrivateService) {
peripheral.discoverCharacteristics(nil, for: s)
}
}
}
}
, , :
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
NSLog("characteristics for service %@", service.uuid.uuidString)
if let characteristics = service.characteristics {
for c in characteristics {
if c.uuid.isEqual(mchpDataPrivateChar) {
peripheral.setNotifyValue(true, for: c)
dataChar = c
}
}
}
}
, , , uuid mchpDataPrivateChar. :
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
NSLog("update value for %@", characteristic.uuid)
if let d = characteristic.value {
var s : String = String()
for b in d {
s.append(Character(UnicodeScalar(b)))
}
NSLog("received \(d.count) bytes: \(s)")
}
}
iOS. :
@IBAction func sendClicked(_ sender: Any) {
if let d = dataChar, let s=sendEdit.text {
let buffer : [UInt8] = Array(s.utf8)
let data : Data = Data(buffer)
periph.writeValue(data, for: d, type: .withResponse)
}
}