0

我对 Swift 很陌生,所以也许我的问题的答案对你来说似乎很容易。我想创建一个接口来扫描 BLE 设备,在 TableView 中列出它们,并连接到此列表中的选定设备。到目前为止,我实现了扫描和列出,但我想知道如何才能连接到您刚刚在 tableview 中单击的所需设备。我假设我必须将外围对象发送到 tableview DidSelectRowAtIndexPath 函数,但我真的不知道该怎么做。或者肯定有更聪明的方法来做到这一点?感谢您的回答和时间

这是我到目前为止所做的:

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

顺便说一句,我到处都读到 CoreBluetooth 正在处理 BLE。那么我用什么来连接没有BLE设备?

4

1 回答 1

1

在数组中添加 CBPeripheral 项而不是名称,然后将该对象传递给 connect 。像下面这样的一些可能会为您解决。首先在您的 didDiscoverPeripheral 中更改此行

items += ["\(peripheral.name)"]

items += [peripheral]

然后在你的 cellForRowAtIndexPath 中更改这一行

cell.textLabel?.text = self.items[indexPath.row]

cell.textLabel?.text = self.items[indexPath.row].name

然后在你的 didSelectRowAtIndexPath

self.manager.connectPeripheral(peripheral, options: nil)

self.manager.connectPeripheral(self.items[indexPath.row], options: nil)
于 2015-10-07T13:55:42.460 回答