我是蓝牙和Swift的新手,现在,我正在尝试简单地连接到蓝牙设备(Arduino HM-10)并获得服务。我遇到的问题是,在连接到设备后,从未调用centralManager didConnectPeripheral方法。这是我的代码
import UIKit
import CoreBluetooth
class ViewController: UIViewController, CBCentralManagerDelegate, CBPeripheralDelegate {
var manager:CBCentralManager!
var peripheral:CBPeripheral!
let BubbleWallBluetoothName = "TestBluetooth"
let BEAN_SCRATCH_UUID =
CBUUID(string: "a495ff21-c5b1-4b44-b512-1370f02d74de")
let BEAN_SERVICE_UUID =
CBUUID(string: "a495ff20-c5b1-4b44-b512-1370f02d74de")
override func viewDidLoad() {
super.viewDidLoad()
manager = CBCentralManager(delegate: self, queue: nil)
}
func centralManagerDidUpdateState(_ central: CBCentralManager){
switch (central.state)
{
case . unsupported:
print("BLE is unsupported")
case.unauthorized:
print("BLE is unauthorised")
case.unknown:
print("BLE is unknown")
case.resetting:
print("BLE is resetting")
case.poweredOff:
print("BLE is powered off")
case.poweredOn:
print("BLE is powered on")
central.scanForPeripherals(withServices: nil, options: nil)
}
}
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
print("Found Device " + peripheral.name!)
let device = (advertisementData as NSDictionary).object(forKey: CBAdvertisementDataLocalNameKey) as? NSString
if (device?.contains(BubbleWallBluetoothName) == true) {
self.manager.stopScan()
self.peripheral = peripheral
self.peripheral.delegate = self
manager.connect(peripheral, options: nil)
}
}
//This function never gets called
func centralManager(central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) {
peripheral.discoverServices(nil)
print("We are connected to BT");
}
}
答案 0 :(得分:0)
好的,所以我设法通过用
替换最后一个方法来使其工作func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
peripheral.discoverServices(nil)
print("We are connected to BT");
}