ios - CBCentralManager 未连接

标签 ios swift core-bluetooth

我正在尝试通过附近的蓝牙设备进行连接。我能够发现但无法连接它们。

这个代表正在工作,但在发现我正在尝试连接其中一个外围设备之后

func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {

        if let device = (advertisementData as NSDictionary).object(forKey: CBAdvertisementDataLocalNameKey) as? String {
            print(device)
            if device.contains("BODY") {
                self.connectPeripheral = peripheral
                self.connectPeripheral.delegate = self
                self.manager.connect(connectPeripheral, options: nil)
               self.manager.stopScan()
            }
        }
    }

这两个委托(delegate)方法没有调用。其中之一应该被调用。

func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        peripheral.delegate = self
        peripheral.discoverServices(nil)
    } 



func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
    //NSLog("Error %@", error.debugDescription)
    print(error.debugDescription)
}

最佳答案

您需要保持对 CBPeripheral 实例的强引用,因为一旦您告诉 Central 停止扫描,它就会释放所有发现的外围设备。

关于ios - CBCentralManager 未连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43739125/

相关文章:

ios - 无法在 iOS11.3 中的 WKWebView POST 请求上设置 httpBody

ios - Sierra : Keychain ignores access control settings and UI-prompts for permission 中的安全/代码设计

ios - 执行 UIKit 动画 block ,例如 animateWithDuration :animations:completion use CADisplaylink?

swift - 需要通用的 FetchedResultsController 构建器(Swift)

swift - 使用 Swift 和 CoreBluetooth 创建静态特性

ios - Swift - 从另一个 ViewController 在 TableView 中插入项目

ios - 如何在 iOS 中以编程方式预选多选 UITableView 中的单元格

ios - 如何以 iOS 端为中心控制扫描请求?

ios - 当应用程序终止时,BLE 设备如何调用应用程序

swift - 从 LinkingObjects 列表中删除特定对象 - Realm Swift