【问题标题】:Bluetooth BLE Device disconnects as soon as connected?蓝牙 BLE 设备一连接就断开连接?
【发布时间】: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 并将其存储在其中
  • 感谢您的推荐,我会这样做的! :)

标签: ios xcode swift bluetooth


【解决方案1】:

您提到的更多是预期的行为。 BTLE 旨在消耗非常少的能量,因此它会尽快断开连接。如果您不需要永久连接,请遵循 发现 --> 连接 --> 读/写 --> 设置计时器 --> 当计时器触发连接时。

如果您需要永久连接,您应该订阅传输实时数据的特性,例如心率应用程序。您需要实现setNotifyValue:forCharacteristic: 方法。阅读Apple Documentation了解更多详情。

【讨论】:

  • 感谢您的帖子!这是一条非常有用的信息,我将阅读并尝试这种实现方法,因为我需要永久连接到我的外围设备。再次感谢!
  • 不用担心。一切顺利。如果这能解决您的问题,请告诉我。也会帮助我指导其他人:)。
猜你喜欢
  • 1970-01-01
  • 2014-07-17
  • 2016-01-30
  • 1970-01-01
  • 2014-05-05
  • 2017-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多