我正在使用BLE通过一个简单的应用程序自动连接我的AirPods。我可以获取设备名称和状态为“connecting”,但由于某种原因,我无法连接它。功能'didConnect peripheral'从未被触发。
我尝试了教程和其他帖子中的所有不同方法,尝试将外围数据存储在数组中以保留引用,但似乎什么都没用。
在“didDiscover”和“didConnect”之间有什么额外的信息可以获得吗?
在iPhone上使用Xcode 9.2,Swift 4和iOS 11.2进行工作。
这是我的代码:
let deviceName = "AirPods de Roger"
var isConnected = false
var manager: CBCentralManager!
var peripheralBLE: CBPeripheral?
override func viewDidLoad() {
super.viewDidLoad()
manager = CBCentralManager(delegate: self, queue: nil)
}
func centralManagerDidUpdateState(_ central: CBCentralManager) {
switch manager.state {
case.poweredOff:
print("BLE service is powered off")
case.poweredOn:
print("BLE service is powered on and scanning")
manager.scanForPeripherals(withServices: nil, options: nil)
default:
print("BLE service in another state")
}
}
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
if peripheral.name == deviceName && isConnected == false {
self.manager.stopScan()
self.peripheralBLE = peripheral
self.peripheralBLE?.delegate = self
manager.connect(peripheral, options: nil)
isConnected = true
print("\(peripheral.name) pre-connected")
}
}
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
lblConnected.isHidden = false
print("AirPods Connected")
peripheral.discoverServices(nil)
}