Swift 3: unable to connect to peripherals via BLE

I am new to BLE, currently trying to create a simple program that will connect to my BLE user device. I can detect a BLE device, but for some reason I cannot connect to it. I tried to test it using Blue, it shows my device as plug-in and seems to work fine. But in my application, after I discovered the device, does the CB manager try to connect to it and it seems to โ€œfreezeโ€? The didConnect peripheral function never fires, and the peripheral state is forever connected.

How can I identify the problem? Are there any options that I can include in the connection method or somehow track the connection process?

I would appreciate any advice on where to look for problems.

Work in Xcode 8.2.1 using Swift 3. iOS 10.2.1 installed on the test phone

Here is my code:

import UIKit import CoreBluetooth class InfoPageViewController: UIViewController, CBCentralManagerDelegate, CBPeripheralDelegate { var manager:CBCentralManager! var peripheral:CBPeripheral! let BEAN_NAME = "MyDevice" override func viewDidLoad() { super.viewDidLoad() manager = CBCentralManager(delegate: self, queue: nil) } 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 { self.manager.stopScan() self.peripheral = peripheral self.peripheral.delegate = self manager.connect(peripheral, options: nil) print("discovered \(BEAN_NAME)") } } func centralManager( central: CBCentralManager, didConnect peripheral: CBPeripheral) { print("connected to \(BEAN_NAME)") peripheral.discoverServices(nil) } 
+5
source share
1 answer
 func centralManager(central: CBCentralManager, didConnect peripheral: CBPeripheral) {} --------------------^ 

Versus:

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

The method signature is incorrect, you are missing _ .

Method signatures are important. We can assume that since delegate delegation methods are optional, internally, Apple code asks itself: Does my delegate have a func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) ( respondsToSelector: method? In your case, no, because it is not the same, and then yours is not called.

You copy / paste the document from the document or delete it and allow Xcode to perform its autocompletion function.

+2
source

Source: https://habr.com/ru/post/1240778/


All Articles