如何在iOS中将蓝牙连接到所选设备

时间:2019-05-17 12:13:05

标签: ios swift core-bluetooth

我是这个CoreBlueTooth主题的新手。在我的应用程序中,我列出了设备列表。我的场景就像敌人的示例,我有两个设备A和B。在A和B设备中,我都在安装应用程序,如果单击“显示设备”按钮,它将显示A和B设备中的设备附近的所有设备。表格检视。如果我在A设备中单击iPhone(列表中的设备名称),并且在B中单击Mi和B(列表中的设备名称),则不应导航到下一个我编写了所有蓝牙代码的视图。正在导航到下一个视图并进行连接,我能够发送数据。我的要求是,如果我在两个设备中均单击iPhone(列表中的设备名称),则它应该验证但无法正常工作。请让我知道如何解决此问题。预先感谢。

**func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber){

    print("Discovered \(peripheral.name) at \(RSSI) and \(peripheral.identifier)")

    if discoveredPeripheral != peripheral {
        // Save a local copy of the peripheral, so CoreBluetooth doesn't get rid of it
        discoveredPeripheral = peripheral

        // And connect
        print("Connecting to peripheral \(peripheral)")
        print("my iden:" ,peripheral.identifier );
        manager.connect(peripheral, options: nil)
    }

    didReadPeripheral(peripheral, rssi: RSSI)
}
func peripheral(_ peripheral: CBPeripheral, didReadRSSI RSSI: NSNumber, error: Error?) {

    didReadPeripheral(peripheral, rssi: RSSI)

    delay(scanningDelay){
        peripheral.readRSSI()
    }
}
func didReadPeripheral(_ peripheral: CBPeripheral, rssi: NSNumber){

    if let name = peripheral.name{

        items[name] = [
            "name":name,
            "rssi":rssi
        ]
    }
    myTablevie.reloadData()
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?)
{
    if let error = error {
        print("error:" ,(error))
        return
    }
    let services = peripheral.services
    print("Found \(services?.count) services! :" , (services))
}
   func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.items.keys.count
}

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)

    // Configure the cell...
    if let item = itemForIndexPath(indexPath){
        cell.textLabel?.text = item["name"] as? String

        if let rssi = item["rssi"] as? Int {
            cell.detailTextLabel?.text = "\(rssi.description) dBm"
        } else {
            cell.detailTextLabel?.text = ""
        }
    }

    return cell
}**

func itemForIndexPath(_ indexPath: IndexPath) -> [String: Any]?{

    if indexPath.row > items.keys.count{
        return nil
    }

    return Array(items.values)[indexPath.row]
}

**func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
    let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let newViewController = storyBoard.instantiateViewController(withIdentifier: "DetailsViewController") as! DetailsViewController
    self.present(newViewController, animated: true, completion: nil)
}**

0 个答案:

没有答案
相关问题