【问题标题】:swift: pair with bluetooth device with button clickswift:通过单击按钮与蓝牙设备配对
【发布时间】:2018-02-26 20:39:17
【问题描述】:

到目前为止,当应用程序打开时 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
    }
}

}

【问题讨论】:

    标签: ios swift bluetooth bluetooth-lowenergy core-bluetooth


    【解决方案1】:

    当您初始化CBCentralManager 并设置它的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)

    【讨论】:

    • 非常感谢:D 这就像一个魅力!我想我必须对代表进行一些阅读。仍在学习基础知识:)
    【解决方案2】:

    不要将函数func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) 放在按钮内。

    试试这个:

    @IBAction func connectBluetooth(_ sender: Any) {
       manager = CBCentralManager(delegate: self, queue: nil)
       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")
            }
        }
    }
    

    在您进行扫描之前,设备知道 BLE 已开启非常重要。

    func centralManagerDidUpdateState(_ central: CBCentralManager) {
            switch (central.state) {
            case .unsupported:
                print("BLE is unsupported")
            case .unauthorized:
                print("BLE is unauthorized")
            case .unknown:
                print("BLE is unknown")
            case .resetting:
                print("BLE is reseting")
            case .poweredOff:
                print("BLE is powered off")
            case .poweredOn:
                print("BLE is powered on")
                //must be called
            }
        }
    

    【讨论】:

    • 谢谢!你所说的 + 移动 manager.scanForPeripherals(withServices: nil, options: nil) 到 case .poweredOn 工作:D
    • 说我错了但是当你把它移到 .poweredOn 时它会被自动调用?
    • 点击按钮后会自动调用(调用 manager = CBCentralManager(delegate: self, queue: nil)。如果我关闭蓝牙,然后再次打开,再次自动调用扫描。希望这回答了你的问题:)
    • 那我误会你了。我以为您只想在按下按钮时进行扫描。但是现在,当您将 BLE 从关闭切换到开启时,您会自动扫描。无论如何,您将其标记为已解决,所以一切都很好
    猜你喜欢
    • 2019-07-12
    • 1970-01-01
    • 1970-01-01
    • 2021-04-26
    • 2016-09-26
    • 2013-06-20
    • 1970-01-01
    • 1970-01-01
    • 2012-12-23
    相关资源
    最近更新 更多