How to bond/pair to a bluetooth LE device programmatically in swift Xcode?

我的梦境 提交于 2021-02-07 09:10:34

问题


I am currently trying to develop and application that allows users to bond to a Peripheral via a click of a button and the password will be automatically entered.

Is it possible to Bond and Remove Bond programmatically using swift?


回答1:


Pairing is initiated any time that you attempt to write to or read from a characteristic on the BLE device. However, if the device is not set to require authentication and/or bonding, you will not see the iOS popup which requests the PIN code.

I struggled with this with my HM-10 because I could write data to the characteristic using the Core Bluetooth (via Swift) function writeValue() without ever seeing the pairing popup.

I couldn't figure it out until I read the HM-10 (implements the IC cc2451) datasheet very closely and found that I needed to set the AT+TYPE to value 3. It defaults to 0 which means that the HM-10 does not require pairing/bonding so you never see the iOS popup.

You can read more about the details where I asked the question and ultimately found the solution and wrote it up: How do I pair and/or bond to BLE on iOS using Swift code and an HM-10 so data sent is encrypted?




回答2:


Follow the step to connect Ble device into iOS Program.

1) Import

import CoreBluetooth

2) Declared the variables into the class or ViewController.

  let kServiceUART = CBUUID(string: "0x1800")
 var peripheralHeartRateMonitor: CBPeripheral?

var cbManger: CBCentralManager!

3) Initialize the cbManger into ViewDidLoad function of viewController or initalize function of class.

  cbManger = CBCentralManager(delegate: self, queue: .main)

4) Override delegate method of the CBCentralManager .

 func centralManagerDidUpdateState(_ central: CBCentralManager) {

    switch central.state {
    case .unsupported:
        print("BLe Unsupported")
        break
    case .unauthorized:
         print("BLe unauthorized")
        break
    case .poweredOff:
        let alertMessgesInst = AlertMessages.sharedInstance
        CommonUtils.showAlert(alertMessgesInst.actofit_Title, message: alertMessgesInst.trun_On_blueTooth)
        break
    case .poweredOn:

        if isNewFirmWareOFImpulse {

            let uuidString = StorageServices.readFromDefaults(key: Constants.userDefaultKeys.impulseUUID)
            let uuid = UUID(uuidString:uuidString as! String )
            let device =  cbManger.retrievePeripherals(withIdentifiers: [uuid!])
            peripheralHeartRateMonitor = device.first
            peripheralHeartRateMonitor!.delegate = self
            cbManger?.connect(peripheralHeartRateMonitor!)

        }else {

            let option:[String: Any] = [CBCentralManagerScanOptionAllowDuplicatesKey: NSNumber(value: false)]
            cbManger.scanForPeripherals(withServices: nil, options: option)
        }

        break
    case .unknown:
         print("BLe unknown")
        break
    default:
        break
    } // End Swith

} // End 'centralManagerDidUpdateState' function.
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {

    if isNewFirmWareOFImpulse {

        peripheralHeartRateMonitor = peripheral
        print("UUid of band is :- \(peripheralHeartRateMonitor?.identifier.uuidString)")

        if impulseName == peripheral.name {


            peripheralHeartRateMonitor!.delegate = self


            cbManger.stopScan()

            // STEP 6: connect to the discovered peripheral of interest
            cbManger?.connect(peripheralHeartRateMonitor!)


        } // End impulse condition

    }else {

        let keysArray = advertisementData.keys

        if let tempImpulseName = peripheral.name {
            print(impulseName + " and " + tempImpulseName )
            if impulseName == tempImpulseName {
                for key in keysArray {
                    if key == "kCBAdvDataManufacturerData"{
                        let manufactureData = advertisementData[key]
                        if let stringValue = manufactureData.debugDescription as? String {

                            var heartValue: String = String()
                            heartValue = stringValue
                            heartValue.removeLast()
                            heartValue.removeLast()
                            let last = heartValue.removeLast()
                            let secondLast = heartValue.removeLast()

                            let hR = String([secondLast, last])
                            if let value = UInt8(hR, radix: 16){

                                if Int(value) > 60 {
                                    hrArray.append(Int(value))
                                }


                            } // End the value block

                        } // end of if 'stringValue' condition
                    } // end 'Key' if condition

                } // End for each loop
            } // End impulse condition

        } // End pheripheral if condition

    } // end version condition

} // End function 'didDiscover peripheral'.

func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {


    // STEP 8: look for services of interest on peripheral

    peripheralHeartRateMonitor?.discoverServices(nil)

} // END func centralManager(... didConnect peripheral

func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
    if error != nil {


来源:https://stackoverflow.com/questions/41690946/how-to-bond-pair-to-a-bluetooth-le-device-programmatically-in-swift-xcode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!