有时,我的应用程序将连接到外围设备(即调用“didConnectPeripheral”)但它不会发现可用服务(不调用“didDiscoverServices”)。此外,当发生这种情况时,外围设备(基于 nRF8001 的 Adafruit Bluefruit)会说它未连接!这种情况只发生在应用程序启动次数的大约 1/5 时。
下面的代码块总是被执行:
func centralManager(central: CBCentralManager!, didDiscoverPeripheral peripheral: CBPeripheral!, advertisementData: [NSObject : AnyObject]!, RSSI: NSNumber!) {
//Connect to the peripheral if its a UART
if(peripheral.name == "UART") {
currentPeripheral = peripheral
currentPeripheral.delegate = self
central.connectPeripheral(currentPeripheral, options: nil)
}
}
func centralManager(central: CBCentralManager!, didConnectPeripheral peripheral: CBPeripheral!) {
println()
println("Connected to: \(peripheral.name)")
peripheral.discoverServices(nil)
connectionStatus = .Connected
central.stopScan()
println("***Stopped scanning***")
}
知道为什么不调用“didDiscoverServices”吗?
(我在第 5 代 iPod touch 上运行该应用程序)
最佳答案
根据CoreBluetooth programming guide ,你应该这样做:
Before you begin interacting with the peripheral, you should set the peripheral’s delegate to ensure that it receives the appropriate callbacks, like this:
peripheral.delegate = self;
因此,您的 didConnectPeripheral 函数应该如下所示:
func centralManager(central: CBCentralManager!, didConnectPeripheral peripheral: CBPeripheral!) {
NSLog("peripheral connected")
peripheral.delegate = self
peripheral.discoverServices(nil)
}
关于IOS 蓝牙未发现外围服务。 (有时!),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29049260/