迅捷:与蓝牙设备配对,单击按钮即可 [英] swift: pair with bluetooth device with button click

查看:97
本文介绍了迅捷:与蓝牙设备配对,单击按钮即可的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

直到现在,当打开应用程序时,iPhone已与蓝牙设备配对,但我想与按钮单击配对.我试图将所有扫描和连接功能放在IBAction中,但是当我按下按钮时什么也没有发生.在IBAction之后的第一个函数中,我有一个打印输出来检查它是否进入了该函数,但是我没有得到打印.我还尝试在manager.scanForPeripherals之后添加延迟,但也没有起作用.我在这里想念什么?有人知道吗? 感谢您的任何答复!这是我的代码(没有延迟):

Until now the iPhone has paired to a bluetooth device when the app is opened, but I want to pair with a button click instead. I tried to put all the scanning and connection functions in a IBAction, but nothing happens when I push the button. In the first function after the IBAction I have a print output to check if it even enters the function, but I don't get the print. I also tried to put a delay after the manager.scanForPeripherals but didn't work either. What am I missing here? anyone know? Thanks for any replies! here is my code (without the delay):

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时,委托将开始接收事件.

When you initialise the CBCentralManager and set its delegate, the delegate will start receiving events.

因此,如果您只希望在用户轻按按钮后才激活CBCentralManager,而不是在屏幕加载后立即激活,则要做的最少工作就是从以下位置移动初始化manager的代码: viewDidLoad进行按钮操作.

So, if you only want the CBCentralManager to be active once the user has tapped a button, rather than as soon as the screen loads, the minimum you have to do is move the code that initialises the manager from viewDidLoad to the button action.

所以:

manager = CBCentralManager(delegate: self, queue: nil)viewDidLoad移动到@IBAction func connectBluetooth(_ sender: Any)

IBAction中删除对scanForPeripherals的呼叫,并且;

Remove the call to scanForPeripherals from the IBAction, and;

取消注释centralManagerDidUpdateState中的// manager.scanForPeripherals(withServices: nil, options: nil).

这篇关于迅捷:与蓝牙设备配对,单击按钮即可的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆