I am trying to develop bluetooth based application that will provide users the functionality to share data via bluetooth pairing. I am facing issue while pairing the device.
This is my scenario The user will login the application and will be prompted to enable bluetooth service. This is the code for the same :-
//MARK: - DECLARATIONS
var cbCentralManager : CBCentralManager?
var peripheral : CBPeripheral?
var peripherals: [CBPeripheral] = []
//MARK: - VIEW_METHODS
override func viewDidLoad() {
super.viewDidLoad()
self.setUpView()
}
func setUpView() {
cbCentralManager = CBCentralManager(delegate: self, queue: nil)
}
//MARK: - EXTENSION
extension ViewController : CBCentralManagerDelegate {
func centralManagerDidUpdateState(_ central: CBCentralManager) {
if central.state == .poweredOn {
print("Bluetooth is enabled..")
central.scanForPeripherals(withServices: nil, options: nil)
} else {
print("Bluetooth is not enabled..")
}
}
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
guard peripheral.name != nil else {return}
print("Sensor Found!")
//stopScan
cbCentralManager?.stopScan()
//connect
cbCentralManager?.connect(peripheral, options: nil)
self.peripheral = peripheral
}
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
//discover all service
peripheral.discoverServices(nil)
peripheral.delegate = self
}
In the next step, on the click of button, near by BLE devices will be scanned.
func startScan() {
let options: [String: Any] = [CBCentralManagerScanOptionAllowDuplicatesKey:
NSNumber(value: false)]
peripherals = []
print("Now Scanning...")
self.timer.invalidate()
centralManager?.scanForPeripherals(withServices: nil, options: options)
Timer.scheduledTimer(timeInterval: 17, target: self, selector: #selector(self.cancelScan), userInfo: nil, repeats: false)
}
After the user selects a device to be paired from the list of scanned BLE devices, below code will be executed for establishing connection between devices.
func connectToDevice(device:CBPeripheral) {
centralManager = CBCentralManager(delegate: self, queue: .main)
self.blePeripheral = device
self.blePeripheral?.delegate = self
centralManager?.connect(self.blePeripheral!, options: nil)
}
The delegate methods are extended
extension HomeVC : CBPeripheralDelegate {
func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
if peripheral.state == .poweredOn {
return
}
print("Peripheral manager is running")
}
//Check when someone subscribe to our characteristic, start sending the data
func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didSubscribeTo characteristic: CBCharacteristic) {
print("Device subscribe to characteristic")
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
print("*******************************************************")
if ((error) != nil) {
print("Error discovering services: \(error!.localizedDescription)")
return
}
guard let services = peripheral.services else {
return
}
//We need to discover the all characteristic
for service in services {
peripheral.discoverCharacteristics(nil, for: service)
// bleService = service
}
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
if ((error) != nil) {
print("Error discovering services: \(error!.localizedDescription)")
return
}
guard let services = peripheral.services else {
return
}
//We need to discover the all characteristic
for service in services {
peripheral.discoverCharacteristics(nil, for: service)
// bleService = service
}
print("Discovered Services: \(services)")
}
func peripheralManagerDidStartAdvertising(_ peripheral: CBPeripheralManager, error: Error?) {
if let error = error {
print("\(error)")
let errorStr = "\(error)"
let alert = UIAlertController(title: "Alert", message: errorStr, preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
return
}
}
}
I am stuck as I am not getting the alert for pairing devices. Can anyone guide me in this ? Thanks in advance.