iOS蓝牙接收数据的方式
蓝牙是一种无线通信技术,广泛应用于移动设备和外部设备之间的数据传输。在iOS开发中,我们可以使用Core Bluetooth框架来实现蓝牙数据的接收。本文将介绍iOS蓝牙接收数据的几种方式,并提供相应的代码示例。
1.通过委托方法接收数据
在iOS开发中,我们可以使用委托方法来接收蓝牙设备传输过来的数据。Core Bluetooth框架提供了CBPeripheralDelegate协议,通过实现该协议中的委托方法来接收数据。
下面是一个简单示例,演示如何使用委托方法接收蓝牙设备传输的数据:
import CoreBluetooth
class BluetoothManager: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate {
var centralManager: CBCentralManager!
var peripheral: CBPeripheral!
override init() {
super.init()
centralManager = CBCentralManager(delegate: self, queue: nil)
}
func centralManagerDidUpdateState(_ central: CBCentralManager) {
if central.state == .poweredOn {
centralManager.scanForPeripherals(withServices: nil, options: nil)
}
}
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
if peripheral.name == "MyBluetoothDevice" {
self.peripheral = peripheral
self.peripheral.delegate = self
centralManager.stopScan()
centralManager.connect(peripheral, options: nil)
}
}
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
peripheral.discoverServices(nil)
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
for service in peripheral.services ?? [] {
peripheral.discoverCharacteristics(nil, for: service)
}
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
for characteristic in service.characteristics ?? [] {
if characteristic.uuid == CBUUID(string: "MyCharacteristicUUID") {
peripheral.setNotifyValue(true, for: characteristic)
}
}
}
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
if let value = characteristic.value {
// 处理接收到的数据
let data = String(data: value, encoding: .utf8)
print("Received data: \(data ?? "")")
}
}
}
在上述代码中,我们创建了一个BluetoothManager
类,该类是一个CBCentralManagerDelegate
和CBPeripheralDelegate
的子类。我们在centralManagerDidUpdateState
方法中,判断蓝牙是否已经打开,如果是,则开始搜索附近的蓝牙设备。
当发现需要连接的蓝牙设备后,我们通过centralManager.connect(_:options:)
方法连接设备,并在didConnect
方法中开始发现设备的服务。
当发现服务后,我们再通过peripheral.discoverCharacteristics(_:for:)
方法发现服务的特征值。然后,我们通过peripheral.setNotifyValue(_:for:)
方法将特征值设置为可通知,这样当蓝牙设备发送数据时,我们就可以接收到数据。
最后,我们在didUpdateValueFor
方法中处理接收到的数据。这里我们将数据转换成字符串并进行打印。
2.使用通知接收数据
除了使用委托方法接收数据外,我们还可以使用通知来接收蓝牙设备传输的数据。Core Bluetooth框架提供了Notification
通知来实现这一功能。
下面是一个示例,演示如何使用通知接收蓝牙设备传输的数据:
import CoreBluetooth
class BluetoothManager: NSObject, CBCentralManagerDelegate {
var centralManager: CBCentralManager!
var peripheral: CBPeripheral!
override init() {
super.init()
centralManager = CBCentralManager(delegate: self, queue: nil)
}
func centralManagerDidUpdateState(_ central: CBCentralManager) {
if central.state == .poweredOn {
centralManager.scanForPeripherals(withServices: nil, options: nil)
}
}
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI