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) }
source share