class PeripheralManager: NSObject, CBPeripheralDelegate, CBPeripheralManagerDelegate, ObservableObject {
private var peripheralManager: CBPeripheralManager?
var serviceUUID = CBUUID(string: "9f37e282-60b6-42b1-a02f-7341da5e2eba")
let characteristicUUID = CBUUID(string: "87654321-4321-8765-4321-876543218765")
private var characteristic: CBMutableCharacteristic?
iOS蓝牙简介
我们可以将iOS设备和MAC设备或者其他更多BLE设备连接起来进行数据的交互。 BLE:bluetouch low energy,蓝牙4.0设备因为低功耗,所有也叫作BLE。 一般应用苹果的官方框架CoreBluetooth开发。 一般我们的设备可以将一端作为中心设备,另一端作为外设设备。发起连接的是中心设备(Central),被连接的是外围设备(Peripheral),对应传统的客户机-服务器体系结构。Central能够扫描侦听到,正在播放广告包的外设。
流程
中心设备Central
主要是用作扫描和连接设备(通过CBService和CBCharacteristic来连接对应的设备)。 具体步骤为:
初始化CBCentralManager
初始化后判断蓝牙状态后开始扫描
继承CBCentralManagerDelegate委托,当扫描到想要设备的时候连接该设备。
连接设备
连接成功后发现服务
/* 订阅特征 / func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) { if let error = error { print("Error discovering characteristics: (error.localizedDescription)") return }
import Foundation import CoreBluetooth
class PeripheralManager: NSObject, CBPeripheralDelegate, CBPeripheralManagerDelegate, ObservableObject { private var peripheralManager: CBPeripheralManager? var serviceUUID = CBUUID(string: "9f37e282-60b6-42b1-a02f-7341da5e2eba") let characteristicUUID = CBUUID(string: "87654321-4321-8765-4321-876543218765") private var characteristic: CBMutableCharacteristic?
// startAdvertising() }
}