而委托不是nil或未实现peripheral:didUpdateValueForCharacteristic:error :?

时间:2019-04-24 09:33:21

标签: ios swift core-bluetooth

在我的应用中,我想通过蓝牙从BLE设备获取电池详细信息。 我是CoreBluetooth框架的新手。

请给我解决方案,了解如何从应用程序中的BLE设备获取数据。

下面是我的ViewController:

import UIKit
import CoreBluetooth

class BluetoothDevicesViewController: UIViewController, CBCentralManagerDelegate, CBPeripheralDelegate {

    @IBOutlet var bluetoothDevicesTableView: UITableView!

    var peripheralsArray = [CBPeripheral]()
    var centralManager: CBCentralManager?

    let YOUR_CHARACTERISTIC_UUID = "47e9ee00-47e9-11e4-8939-164230d1df67"

    var peripheralData = PeripheralData.sharedInstance

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    override func viewDidAppear(_ animated: Bool)
    {
        super.viewDidAppear(animated)
        if peripheralData.peripherals != nil {
            peripheralsArray = peripheralData.peripherals
            bluetoothDevicesTableView.reloadData()
        }
    }

    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        print(central.state)
    }
}

extension BluetoothDevicesViewController: UITableViewDelegate, UITableViewDataSource {

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return peripheralsArray.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "DevicesTableViewCell", for: indexPath) as? DevicesTableViewCell

        let peripheral = peripheralsArray[indexPath.row]
        centralManager?.connect(peripheral, options: nil)

        if peripheral.state == .connected {

            cell?.circleView.backgroundColor = Common.blueColor

            peripheral.delegate = self
            peripheral.discoverServices(nil)

        } else {
            cell?.circleView.backgroundColor = Common.redColor
        }

        cell?.deviceNameLabel.text = peripheral.name
        return cell!
    }

}

运行此命令时,我在控制台上收到警告。

API MISUSE: Discovering services for peripheral <CBPeripheral: 0x282e82a80, identifier = C8C81899-0AC7-B5B6-72F4-5B9631B22D1E, name = mote 200, state = connected> while delegate is either nil or does not implement peripheral:didDiscoverServices:

1 个答案:

答案 0 :(得分:1)

viewDidLoad

centralManager = CBCentralManager(delegate: self, queue: DispatchQueue.global())

func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { 
}

您可以关注bluetooth