how to connect with bluetooth low energy in ios swift?
Asked Answered
K

3

5

I want to connect with ble peripheral. But my code doesn't call didConect function

this is my code :

func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
 let device = (advertisementData as NSDictionary)
            .object(forKey: CBAdvertisementDataLocalNameKey)
            as? NSString

        if device?.contains(BEAN_NAME) == true {

            print("Did discover peripheral", peripheral)

            self.bluetoothManager.stopScan()
            self._peripheral = peripheral
            self._peripheral.delegate = self
            central.connect(peripheral, options: nil)
        }
}


func centralManager( central: CBCentralManager, didConnect peripheral: CBPeripheral) { //cant call this
        print("connected to \(BEAN_NAME)")
        peripheral.discoverServices(nil)
    }

Logs :

BLE service is powered on
Did discover peripheral <CBPeripheral: 0x1740eef00, identifier = 4872623B-F872-443A-8A96-F4E1F84D6841, name = GoDoor in  :), state = disconnected>
Kroo answered 12/4, 2017 at 1:52 Comment(4)
Have you confirmed that your if test is passing? Normally you would save the identifier of the device you are interested in rather looking at the advertisement data.Capelin
yes. Logs print "Did discover peripheral" . When I print something after central.connect, it printed in log. Seems like central.connect not executed.@CapelinKroo
How is _peripheral declared? Have you implemented the didFailToConnect delegate method in case your connection is failing?Capelin
now i can do function didConnect peripheral, it was failed because of "" sign. It must be : func centralManager( central: CBCentralManager, didConnect peripheral: CBPeripheral) thanks for helping @CapelinKroo
K
2

I've solved this.
just need to change :

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

into this :

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

reference : Swift 3: Can't connect to peripheral via BLE

Kroo answered 12/4, 2017 at 3:27 Comment(1)
Good find. Changed delegate method signatures in Swift 3 have burned me before as well, and despite that I didn't spot this looking at your question.Woodyard
P
2

I created a demo project, which scans for Bluetooth LE devices and displays them in a list:

Check it out on github: quickies/BluetoothScanner.ios

Screenshot

Screenshot

Pinkerton answered 27/6, 2017 at 14:19 Comment(0)
M
-1
      @IBAction func btnConnect(_ sender: UIButton){

        self.appDelegate.bleManager.stopScan()

        self.appDelegate.selectPeripheral = self.arrayPeripheral[sender.tag]

        self.appDelegate.bleManager.connect(self.selectPeripheral, options: nil)

      }
Meridithmeriel answered 19/7, 2017 at 12:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.