到目前为止,iPhone 已在打开应用程序时与蓝牙设备配对,但我想通过单击按钮进行配对。我尝试将所有扫描和连接功能放入 IBAction 中,但是当我按下按钮时什么也没有发生。在 IBAction 之后的第一个函数中,我有一个打印输出来检查它是否进入了该函数,但我没有得到打印。我还尝试在 manager.scanForPeripherals 之后延迟,但也不起作用。我在这里缺少什么?有人知道吗? 感谢您的回复!这是我的代码(没有延迟):
var manager: CBCentralManager!
var device: CBPeripheral?
var characteristics: [CBCharacteristic]?
var serviceUUID = "1234"
var char1 = "FFE1"
let deviceName = "HMSoft"
var connected = CBPeripheralState.connected
var disconnected = CBPeripheralState.disconnected
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
manager = CBCentralManager(delegate: self, queue: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func centralManagerDidUpdateState(_ central: CBCentralManager) {
switch central.state {
case .poweredOn: break
// manager.scanForPeripherals(withServices: nil, options: nil)
case .unknown: break
case .resetting: break
case .unsupported: break
case .unauthorized: break
case .poweredOff:
break
}
}
@IBAction func connectBluetooth(_ sender: Any) {
manager.scanForPeripherals(withServices: nil, options: nil)
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
if let peripheralName = advertisementData[CBAdvertisementDataLocalNameKey] as? String {
if peripheralName == self.deviceName {
// save a reference to the sensor tag
self.device = peripheral
self.device!.delegate = self
// Request a connection to the peripheral
self.manager.connect(self.device!, options: nil)
print("Check")
}
}
}
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
peripheral.discoverServices(nil)
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
if error != nil {
return
}
if let services = peripheral.services {
for service in services {
if (service.uuid == CBUUID(string: serviceUUID)) {
peripheral.discoverCharacteristics(nil, for: service)
}
}
}
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
device = peripheral
characteristics = service.characteristics
}
func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
if error != nil {
return
}
}
}
最佳答案
当您初始化CBCentralManager
并设置其委托(delegate)
时,委托(delegate)将开始接收事件。
因此,如果您只希望 CBCentralManager 在用户点击按钮后激活,而不是在屏幕加载后立即激活,那么您至少需要移动初始化代码manager
从 viewDidLoad
到按钮操作。
所以:
将 manager = CBCentralManager(delegate: self,queue: nil)
从 viewDidLoad
移动到 @IBAction func connectBluetooth(_ sender: Any)
,
从 IBAction
中删除对 scanForPeripherals
的调用,并且;
取消注释 centralManagerDidUpdateState
中的 //manager.scanForPeripherals(withServices: nil, options: nil)
。
关于ios - swift:通过单击按钮与蓝牙设备配对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48996717/