如何快速蓝牙连接设备?

时间:2019-09-03 07:50:51

标签: 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)
    }


}

2 个答案:

答案 0 :(得分:0)

可能您需要将以下内容添加到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)
}

答案 1 :(得分:0)

如果要发送消息,则应使用所连接的当前外围设备的功能 writeValue

例如

let messageToSend = "HelloWorld!"
peripheral.writeValue(messageToSend.data(using: .utf8)!, for: char, type: .withResponse)

要检查函数是否处理了一些错误,可以使用此委托

 func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) { }

查找所有特征

func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        peripheral.discoverServices(nil)
    }

    func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
        if let services = peripheral.services {
            for service in services {
                peripheral.discoverCharacteristics(nil, for: service)
            }
        }
    }

    func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
        if let characteristics = service.characteristics {
            for char in characteristics {
                let messageToSend = "HelloWorld!"
                peripheral.writeValue(messageToSend.data(using: .utf8)!, for: char, type: .withResponse)
            }
        }
    }