【发布时间】:2015-12-18 01:41:04
【问题描述】:
我一直在使用 Swift 编写一个连接到蓝牙 BLE 设备的应用程序。出于某种原因,该应用程序并不总是连接到设备。在这种情况下,它将连接但立即断开连接。这只发生在它连接的 10 次中可能只有 1 次,但肯定会干扰应用程序的可靠性。
我正在使用CoreBluetooth 连接到 BLE 设备。再次尝试连接通常总是让它重新连接,并且与此设备通信的其他应用程序每次都能正常工作,所以我相信这不是外围设备的问题。
我只是想知道是否有人遇到过类似的问题,或者是否有特定原因导致这种情况发生?
编辑:这是我的表的 willSelectRow 的代码。这是我连接外围设备的地方。
func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
centralManager.stopScan()
connectingPeripheral.append(discoveredDeviceArrayInfo[indexPath.row])
connectPeripheralNow(connectingPeripheral[0])
return indexPath
}
这是我连接它的地方,此时我选择设置要连接的设备的 CBPeripheral 详细信息的行。
connectPeripheral现在看起来像这样:
func connectPeripheralNow(peripheral: CBPeripheral!){
self.centralManager.connectPeripheral(peripheral, options: nil)
}
didConnectPeripheral 和 didDiscoverServices 看起来像这样
func centralManager(central: CBCentralManager,didConnectPeripheral peripheral: CBPeripheral)
{
peripheral.delegate = self
peripheral.discoverServices([CBUUID(string: "FFE5")])
print("SUCCESS: Connected to " + peripheral.name!)
}
func peripheral(peripheral: CBPeripheral, didDiscoverServices error: NSError?)
{
if let servicePeripherals = peripheral.services as [CBService]!
{
for servicePeripheral in servicePeripherals
{
print("INFORMATION: Service discovered " + String(stringInterpolationSegment: servicePeripheral.UUID))
peripheral.discoverCharacteristics(nil, forService: servicePeripheral)
}
}
}
仅供参考,我确实收到了“成功:已连接到 xxx”消息,表明它正在连接。如果您需要更多代码,请告诉我!
【问题讨论】:
-
可以添加委托方法的代码吗?
-
感谢您的回复!我在编辑部分添加了一些代码。如果您需要更多代码,请告诉我!
-
确保将要连接的外围设备存储在一个强变量中 - 它在您的
connectingPeripheral数组中,但如果它从该数组中删除,那么它将被释放并且连接将失败。我建议您创建另一个属性/iVar,例如connectedPeripheral并将其存储在其中 -
感谢您的推荐,我会这样做的! :)