应用程序在连接到蓝牙设备后不打印文本 (Swift)

App not printing text after connecting to bluetooth device (Swift)

我目前正在尝试制作一个连接到蓝牙设备的应用程序,完成后打印出

连接后我遇到了问题,它没有打印出服务而是打印出 "while delegate is either nil or does not implement peripheral:didDiscoverServices:"。但问题是我确实有 didDiscoverServices.

这是我的viewcontroller

import UIKit
import CoreBluetooth

let rowerServiceCBUUID = CBUUID(string: "CE060000-43E5-11E4-916C-0800200C9A66")

class HRMViewController: UIViewController {

  @IBOutlet weak var heartRateLabel: UILabel!
  @IBOutlet weak var bodySensorLocationLabel: UILabel!
  var centralManager: CBCentralManager!
  var pmPeripheral: CBPeripheral!
  override func viewDidLoad() {
    super.viewDidLoad()
    centralManager = CBCentralManager(delegate: self, queue: nil)
    // Make the digits monospaces to avoid shifting when the numbers change
    heartRateLabel.font = UIFont.monospacedDigitSystemFont(ofSize: heartRateLabel.font!.pointSize, weight: .regular)
  }

  func onHeartRateReceived(_ heartRate: Int) {
    heartRateLabel.text = String(heartRate)
    print("BPM: \(heartRate)")
  }
}
extension HRMViewController: CBCentralManagerDelegate {
  func centralManagerDidUpdateState(_ central: CBCentralManager) {
    switch central.state {
    case .unknown:
      print("central.state is .unknown")
    case .resetting:
      print("central.state is .resetting")
    case .unsupported:
      print("central.state is .unsupported")
    case .unauthorized:
      print("central.state is .unauthorized")
    case .poweredOff:
      print("central.state is .poweredOff")
    case .poweredOn:
      print("central.state is .poweredOn")
      centralManager.scanForPeripherals(withServices: [rowerServiceCBUUID])
    @unknown default: break

    }
  }

  func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
    print(peripheral)
    pmPeripheral = peripheral
    centralManager.stopScan()
    centralManager.connect(pmPeripheral!)
  }
  func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
    print("Connected!")
    pmPeripheral.discoverServices(nil)
  }
}
extension HRMViewController: CBPeripheralDelegate {
  func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
    guard let services = peripheral.services else { return }

    for service in services {
      print(service)
      pmPeripheral.delegate = self
    }
  }
}

有人知道我该怎么做吗?谢谢

虽然您设置了中央管理器的委托,但您还没有设置外围设备的委托。在centralManager(_,didDiscover,advertisementData)中添加:

pmPeripheral.delegate = self

这应该会解决您的警告并且将调用委托方法。