ios - swift:通过单击按钮与蓝牙设备配对

标签 ios swift bluetooth bluetooth-lowenergy core-bluetooth

到目前为止,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 在用户点击按钮后激活,而不是在屏幕加载后立即激活,那么您至少需要移动初始化代码managerviewDidLoad 到按钮操作。

所以:

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/

相关文章:

ios - 单击相应按钮后如何转到标签栏 Controller

json - 从类中过滤数组

swift - UITextField.text 值不会在 GooglePlaceAutocomplete 上改变

linux - BlueZ:如何从命令行设置 GATT 服务器

ios - 您如何调试 iOS 中 Release模式构建的问题?

ios - Swift TableView segue to new ViewController with wrong index path (倒数第二个选择)

ios - 在 UITableViewCell 中滑动手势 UIImageView

android - 对蓝牙配对对话输入的 react

iphone - 如何使用 iPhone 与 IDBlue RFID 笔通信 RFID 标签?

ios - Realm Swift iOS - 无法设置主键