swift - 如何快速蓝牙连接设备?

标签 swift bluetooth connect

import Foundation


struct BluetoothStruct {
    var name : String?
    var rssi : NSNumber!
    var advertisementData: [String : Any]!
    var uuid : String!
}



import UIKit
import CoreBluetooth


class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, CBCentralManagerDelegate,CBPeripheralDelegate {

    var allBluetoothArray = [BluetoothStruct]();
    var arrayPeripehral = [CBPeripheral]()
    var cbCentralManager : CBCentralManager?

    var manager:CBCentralManager!
    var peripheral:CBPeripheral!

    //MARK: - IBOutlets
    @IBOutlet weak var table: UITableView!


    //MARK: - IBActions
    @IBAction func refreshAction(_ sender: Any) {
        allBluetoothArray = [BluetoothStruct]();
        table.reloadData();

        cbCentralManager?.stopScan();
        cbCentralManager?.scanForPeripherals(withServices: nil, options: nil);

    }



    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        table.delegate = self;
        table.dataSource = self;

        cbCentralManager = CBCentralManager(delegate: self, queue: nil);
    }


    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return allBluetoothArray.count;
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = table.dequeueReusableCell(withIdentifier: "BluetoothCell", for: indexPath) as! BluetoothTableViewCell;

        if let name = allBluetoothArray[indexPath.row].name {
            cell.deviceName.text = "Bluetooth Aygıt Adı: \(name)"
        }else{
            cell.deviceName.text = "Bluetooth Aygıt Adı: \(allBluetoothArray[indexPath.row].uuid)"
        }

        cell.deviceSignal.text = "RSSI: \(allBluetoothArray[indexPath.row].rssi)"


        return cell;
    }


    //MARK: - Bluetooth Functions
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        if central.state == .poweredOn {
            central.scanForPeripherals(withServices: nil, options: nil);
        }else{
            print("Bluetooth'un çalışmıyor, lütfen düzelt");
        }
    }


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

        var bluetoothStruct = BluetoothStruct();

        if let name = peripheral.name{
            bluetoothStruct.name = name;
        }

        bluetoothStruct.uuid = peripheral.identifier.uuidString;
        bluetoothStruct.rssi = RSSI;
        bluetoothStruct.advertisementData = advertisementData;

        if !(allBluetoothArray.contains(where: {$0.uuid == peripheral.identifier.uuidString})){
            allBluetoothArray.append(bluetoothStruct);
            arrayPeripehral.append(peripheral)
            //print(allBluetoothArray)
        }

        table.reloadData();
    }


    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print(allBluetoothArray[indexPath.row])
        print(allBluetoothArray[indexPath.row].name)
        print(allBluetoothArray[indexPath.row].rssi)
        print(allBluetoothArray[indexPath.row].advertisementData)
        print(allBluetoothArray[indexPath.row].uuid)

        let peripheral = arrayPeripehral[indexPath.row]
        cbCentralManager?.connect(peripheral,options: nil)
    }


}

最佳答案

可能您需要将以下内容添加到您的 ViewController

func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {

    peripheral.delegate = self

    print("Connected peripheral: \(peripheral.name ?? "UNKNOWN NAME")")
}

func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {

    for service in peripheral.services ?? [] {
        print("Discovered service: \(service.uuid.uuidString)")
    }
}

func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {

    for char in service.characteristics ?? [] {
        print("Discovered char: \(char.uuid.uuidString)")
    }
}

或者在连接到设备之前设置代理

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print(allBluetoothArray[indexPath.row])
    print(allBluetoothArray[indexPath.row].name)
    print(allBluetoothArray[indexPath.row].rssi)
    print(allBluetoothArray[indexPath.row].advertisementData)
    print(allBluetoothArray[indexPath.row].uuid)

    let peripheral = arrayPeripehral[indexPath.row]

    peripheral.delegate = self // <=== THIS LINE

    cbCentralManager?.connect(peripheral,options: nil)
}

关于swift - 如何快速蓝牙连接设备?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57767243/

相关文章:

javascript - "end"来自 express/connect 中间件的请求的正确方法是什么?

ios - navigationBar.isHidden 和 setNavigationBarHidden 的区别

android - 在 Android 4.3 蓝牙 BLE 上重置蓝牙芯片后调用 BluetoothGatt.connect() 时捕获 DeadObjectException

matlab - 在 MATLAB 中获取连续输入

java - EV3 Lejos蓝牙发送和接收数据

node.js - nodejs : where session stores? 什么是connect-mongo?

swift - 停止 UIButton 淡出 - Swift

ios - UIAlertController 的 NSNotification

ios - 无法将类型 'NSURL.Type' 的值转换为预期的参数类型 'NSURL?'

javascript - npm 卸载后,Express 包仍然是 "require"吗?