美文网首页
Swift3.0 蓝牙使用(多连接简单介绍)

Swift3.0 蓝牙使用(多连接简单介绍)

作者: BrumeLoong | 来源:发表于2017-11-11 15:07 被阅读0次

iOS BLE开发调用的是CoreBluetooth系统原生库,基本用到的类有:

CBCentralManager //系统蓝牙设备管理对象

CBPeripheral //外围设备

CBService //外围设备的服务或者服务中包含的服务

CBCharacteristic //服务的特性

CBDescriptor //特性的描述符

使用(部分代码)

蓝牙连接实例化

myCentralManager = CBCentralManager()

myCentralManager.delegate = self

开始搜索蓝牙

myCentralManager.scanForPeripherals(withServices: nil, options: nil)

发现设备调用

func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {

central.connect(self.myPeripheral, options: nil)

}

设备已经接成功

func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {

}

设备连接断开

func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {

}

设备连接失败

func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?){

}

发现服务调用

func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {

for s in peripheral.services!{

peripheral.discoverCharacteristics(nil, for: s)

}

}

根据服务找特征

func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {

print("----发现特征------")

for c in service.characteristics! {

if c.uuid.uuidString == CHARACTERISTIC{

self.writeCharacteristic = c

peripheral.setNotifyValue(true, for: c)

}

}

}

获取蓝牙设备返回的数据

    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?){

}

发送指令到设备

func writeToPeripheral(_ bytes:[UInt8]) {

if writeCharacteristic != nil {

let data1:Data = dataWithHexstring(bytes)

self.myPeripheral.writeV    alue(data1, for: writeCharacteristic, type: CBCharacteristicWriteType.withResponse)

} else{

}

}

写入后的回调方法

func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {

print("didWriteValueForCharacteristic")

}

以上只是作为蓝牙从连接打到发送数据接收数据的一个简单流程,蓝牙也可以作为多连接,在数据返回的方法可以对返回的蓝牙设备和你连接的所有蓝牙设备进行一个判断,根据判断来断定是哪个蓝牙设备返回过来的信息。

另外关于蓝牙的UUID,听说是每个手机连接同一个蓝牙设备的UUID会不同,这方面安卓那边比较简单的能获取到蓝牙的Mac地址,iOS好像要和厂家那边协商一下,我以为你懒得去弄 了所有就暂时这样;手上我也只有1个手机所有没有做这方面的测试,有看到这篇文件的朋友或者知道的大神可以留言告诉我是否是这样的。

相关文章

网友评论

      本文标题:Swift3.0 蓝牙使用(多连接简单介绍)

      本文链接:https://www.haomeiwen.com/subject/epwwmxtx.html