我知道提到的断开连接错误在堆栈上被问了很多次,但接受的答案并不是问题的实际解决方案
我正在尝试将 MI Band 3 与我的 swift 应用程序连接。连接成功,但一段时间后自动断开
Error: Error Domain=CBErrorDomain Code=7 "The specified device has disconnected from us." UserInfo={NSLocalizedDescription=The specified device has disconnected from us
我的应用需求:我需要从Apple Watch、Fitbit和小米智能手表获取心率和步行距离
我尝试在多个设备上连接相同的 MI Band,结果是相同的。但那个特定的 MI 乐队与他们自己的应用程序完美配合
--> Connect Device - Kept reference of connected Device
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
print("Connected With Peripheral: \(peripheral)")
selectedPeripheral=peripheral
self.delegate?.scannedPeripherals(Is: peripheral)
/// Discover Services Provided By Device
selectedPeripheral?.delegate=self
selectedPeripheral?.discoverServices([heartRateServiceCBUUID])
}
---> After Discovering services With heart Rate CBUUID
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
guard let characteristics = service.characteristics else { return }
selectedPeripheral=peripheral
for char in characteristics {
print("Characterstics: \(char)")
if char.properties.contains(.read) {
}
if char.properties.contains(.notify) {
/// ------------- Setting Notify to true but not never call required delegates ----------------
peripheral.setNotifyValue(true, for: char)
print("\(char.uuid): properties contains .notify")
peripheral.readValue(for: char)
}
}
}
Calculating BPM from delegate
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
switch characteristic.uuid {
case bodySensorLocationCharacteristicCBUUID:
let bodySensorLocation = bodyLocation(from: characteristic)
print(bodySensorLocation)
default:
/// --------- here characteristic value is nil --------------
let bpm = heartRate(from: characteristic)
print("BPM: \(bpm)")
}
}
在
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?)
尝试删除
peripheral.readValue(for: char)
并再次测试!
只需删除此行
peripheral.readValue(for: char)
现在一切都会按预期进行