I'm very new to Swift so maybe the answer to my question will seem easy to you. I want to create an interface to scan BLE devices, list them in a TableView, and connect to the selected device in this list. So far, i achieved to scan and list, but i wonder how i can do to connect to the desired device you just clicked in the tableview. I assume i have to send peripheral object to tableview DidSelectRowAtIndexPath function, but i really don't know how to do this. Or surely there's a smarter way to do this ? Thanks for your answers and time
Here's what i've done so far :
import UIKit
import CoreBluetooth
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, CBCentralManagerDelegate, CBPeripheralDelegate, UITextViewDelegate {
@IBOutlet var status: UITextView!
@IBOutlet
var manager:CBCentralManager!
var tableView: UITableView!
var items: [String] = [""]
override func viewDidLoad() {
super.viewDidLoad()
manager = CBCentralManager(delegate: self, queue: nil)
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
status!.delegate = self
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.items.count; }
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell!
cell.textLabel?.text = self.items[indexPath.row]
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
status.text = "Connexion en cours";
self.manager.connectPeripheral(peripheral, options: nil) // HERE IS THE THING...
}
func centralManagerDidUpdateState(central: CBCentralManager) {
if central.state == CBCentralManagerState.PoweredOn {
central.scanForPeripheralsWithServices(nil, options: nil)
status.text = "Recherche d'appareil Bluetooth";
}
if central.state == CBCentralManagerState.PoweredOff { status.text = "Le Bluetooth est éteint"; }
if central.state == CBCentralManagerState.Unsupported { status.text = "Le Bluetooth n'est pas supporté"; }
if central.state == CBCentralManagerState.Unauthorized { status.text = "Le Bluetooth n'est pas autorisé"; }
}
func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) {
items += ["\(peripheral.name)"]
self.tableView.reloadData()
self.manager.stopScan()
}
func centralManager(central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) {
status.text = "Connecté au périphérique";
//peripheral.discoverServices(nil)
}
}
By the way, i read everywhere that CoreBluetooth was dealing with BLE. So what do i use to connect no BLE device ??