Hello,
I am trying to get my head around the CoreBluetooth framework. From different code samples I found here and there I managed to write a very simple script that scans for Bluethooth peripherals but I a m a bit puzzled by the result.
Why do I get duplicates in the list of peripherals ? (typically my iPad almost always appears twice)
Why do I sometime get a "nil" peripheral ?
<CBPeripheral: 0x1c011a040, identifier = A02449FF-A70C-92FC-1950-9DDFC0709126, name = Adafruit, state = disconnected>
what is 0x1c011a040 ?
Thanks !
//
// ViewController.swift
// BLE2
//
// Created by UoC on 15/10/2018.
// Copyright © 2018 Matt. All rights reserved.
//
import UIKit
import CoreBluetooth
let myCBUUID = CBUUID(string: "0x1c01135f0")
class ViewController: UIViewController {
// Variables
var myCentralManager: CBCentralManager!
var myPeripherals = Array<CBPeripheral>()
// IBOutlets
@IBOutlet weak var myTableView: UITableView!
// Functions
override func viewDidLoad() {
super.viewDidLoad()
myCentralManager = CBCentralManager(delegate: self, queue: nil)
myTableView.dataSource = self
}
}
// Class extensions
extension ViewController:UITableViewDataSource{
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myPeripherals.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let myCell = myTableView.dequeueReusableCell(withIdentifier: "myReusableIdentifier")!
let myPeripheral = myPeripherals[indexPath.row]
myCell.textLabel?.text = myPeripheral.name
return myCell
}
}
extension ViewController: CBCentralManagerDelegate{
func centralManagerDidUpdateState(_ central: CBCentralManager) {
if central.state == .poweredOn {
print("powered on")
myCentralManager.scanForPeripherals(withServices: nil, options: nil) // withServices: nil or [myCBUUID]
}
}
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String: Any], rssi RSSI: NSNumber) {
print(peripheral.name as Any)
//print(RSSI)
//print(UUID.self)
//print(myPeripherals)
myPeripherals.append(peripheral)
myTableView.reloadData()
}
}