Swift 4 BLE centralManager didConnect

时间:2018-08-27 22:43:57

标签: ios swift bluetooth-lowenergy core-bluetooth

那里有一些相关的帖子,但是没有一个对我有帮助。.我无法成功连接到我的蓝牙设备。代码如下:

import UIKit
import CoreBluetooth

class WorkoutViewController: UIViewController, CBCentralManagerDelegate, CBPeripheralDelegate {

var centralManager: CBCentralManager!
var bikeDataPeripheral: CBPeripheral?

override func viewDidLoad() {
    super.viewDidLoad()

    // bt initialization
    centralManager = CBCentralManager(delegate: self, queue: nil) 
}

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: nil)
    }
}

func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
    print(peripheral)
    if peripheral.name == "M3" {
        centralManager.stopScan()
        self.bikeDataPeripheral = peripheral
        bikeDataPeripheral?.delegate = self
        centralManager.connect(peripheral)
    }
}

func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
    print("Connected!")
    bikeDataPeripheral?.discoverServices(nil)
}
}

问题是“已连接!”信息永远不会打印。好像我陷入了“连接”状态,但手机从未完全连接到BLE设备/外围设备

0 个答案:

没有答案