I have the following very simple code snippet on El Capitan which is basically scanning BLE peripherals and connecting to the one I want. However, didDiscoverPeripheral is never called! It starts scanning but never finds any peripheral. A few answers to future clarification requests:
I have BLE devices advertising in the vicinity. I can see them from the phone for example.
The code checks if the BLE is poweredOn.
There are many similar questions such as below but none of them have the working answer for me.
The code is as follows:
import Cocoa
import CoreBluetooth
class ViewController: NSViewController, CBPeripheralDelegate, CBCentralManagerDelegate {
var centralManager: CBCentralManager!
var peripheral: CBPeripheral!
let DEVICE_NAME = "something"
var currentCharacteristic: CBCharacteristic! = nil
// Put CentralManager in the main queue
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.startManager()
}
override func viewDidLoad() {
super.viewDidLoad()
self.startManager()
// Do any additional setup after loading the view.
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
func startManager(){
centralManager = CBCentralManager(delegate: self, queue: DispatchQueue.main)
}
func centralManagerDidUpdateState(_ central: CBCentralManager) {
switch (central.state)
{
case CBCentralManagerState.unsupported:
print("BLE Unsupported")
break
case CBCentralManagerState.unauthorized:
print("BLE unauthorized")
break
case CBCentralManagerState.poweredOff:
print("BLE is not on.")
break
case CBCentralManagerState.poweredOn:
print("BLE is on.")
print("Scanning...")
self.centralManager?.scanForPeripherals(withServices: nil, options: nil)
break
case CBCentralManagerState.unknown:
print("BLE state unknown")
break
default:
print("BLE state default.")
}
}
func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) {
// This is NEVER called!
print("Peripheral: \(peripheral)")
if (peripheral.name != nil && peripheral.name! == DEVICE_NAME){
self.peripheral = peripheral
self.centralManager.connect(self.peripheral, options: [CBConnectPeripheralOptionNotifyOnDisconnectionKey : true])
}
}
func centralManager(central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) {
peripheral.delegate = self
peripheral.discoverServices(nil)
print("Connected to \(peripheral)")
self.stopScan()
}
func centralManager(central: CBCentralManager, didFailToConnectPeripheral peripheral: CBPeripheral, error: NSError?){
print("connection failed", error)
}
func stopScan(){
self.centralManager.stopScan()
}
func centralManager(central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: NSError?){
if self.peripheral != nil {
self.peripheral.delegate = nil
self.peripheral = nil
}
print("Disconnected.", error)
self.startManager()
}
}
Any idea what's wrong?