swift - 扫描 BLE 外设并连接到它

标签 swift xcode bluetooth bluetooth-lowenergy

总体而言,对于 BLE 和移动应用程序编码还相当陌生。我尝试了几个演示并遇到了这个 https://github.com/RickRedSix/BLE4.0-iOS-Swift-Demo 问题是它没有连接到我的 BLE 设备,所以我假设它只扫描当时的 BLE 设备创建者,所以我总是收到错误“只能在开机状态下接受此命令”。我需要更改代码中的任何部分以使其扫描另一个外围设备吗?我是否需要在某处指定设备的 UUID、MAC 地址或其他唯一信息?

感谢对此问题的任何帮助

最佳答案

大约一年前,我开发了一个应用程序来扫描并连接到 BLE 设备。发布该项目的代码。如果你按原样复制粘贴它可能不起作用。但我 100% 确定这正是您想要实现的目标。

我也使用“https://github.com/RickRedSix/BLE4.0-iOS-Swift-Demo”作为引用。

希望这能帮助您解决问题。如果您有任何疑问,请告诉我。

import UIKit
import CoreLocation
import CoreBluetooth

class BLEDeviceTableViewController: UIViewController, CLLocationManagerDelegate, UITableViewDelegate, UITableViewDataSource, CBCentralManagerDelegate, CBPeripheralDelegate {

private var myTableView: UITableView!

var manager : CBCentralManager!
var myBluetoothPeripheral = [CBPeripheral]()
var myCharacteristic : CBCharacteristic!

var isMyPeripheralConected = false

var peripheralNames = [String]()


override func viewDidLoad() {
    super.viewDidLoad()

    let displayWidth: CGFloat = self.view.frame.width

    manager = CBCentralManager(delegate: self, queue: nil)

    myTableView = UITableView(frame: CGRect(x: 0, y: 135, width: displayWidth, height: (self.view.frame.height-(self.view.frame.height/3))-10))
    myTableView.register(UITableViewCell.self, forCellReuseIdentifier: "MyCell")
    myTableView.dataSource = self
    myTableView.delegate = self
    self.view.addSubview(myTableView)

    // Do any additional setup after loading the view.
}

func centralManagerDidUpdateState(_ central: CBCentralManager) {

    var msg = ""

    switch central.state {

    case .poweredOff:
        msg = "Bluetooth is Off"
    case .poweredOn:
        msg = "Bluetooth is On"
        manager.scanForPeripherals(withServices: nil, options: nil)
    case .unsupported:
        msg = "Not Supported"
    default:
        msg = "😔"

    }

    print("STATE: " + msg)

}

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



    peripheralNames.append(peripheral.name ?? "Unknown Device")
    print(peripheral)


    self.myBluetoothPeripheral.append(peripheral)      //save peripheral

    print(peripheralNames)
    myTableView.reloadData()
}

func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
    print("Connected to \(peripheral.name ?? "Uknown Device")")
    availableDeviceLabel.text = "Connected to \(peripheral.name ?? "Uknown Device")"
    isMyPeripheralConected = true //when connected change to true
    peripheral.delegate = self
    peripheral.discoverServices(nil)
}

func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
    isMyPeripheralConected = false //and to falso when disconnected
}


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

    print("Services:\(String(describing: peripheral.services)) and error\(String(describing: error))")
    if let services = peripheral.services {
        for service in services {
            peripheral.discoverCharacteristics(nil, for: service)
        }
    }

}

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


    print("peripheral:\(peripheral) and service:\(service)")

    for characteristic in service.characteristics!
    {
        peripheral.setNotifyValue(true, for: characteristic)
    }

}

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

    let readValue = characteristic.value

    print("Response from BLE Device: \(readValue)")

}

//if you want to send an string you can use this function.
func writeValue() {

    if isMyPeripheralConected {

        //check if myPeripheral is connected to send data

        //let dataToSend: Data = "Hello World!".data(using: String.Encoding.utf8)!

        //myBluetoothPeripheral.writeValue(dataToSend, for: myCharacteristic, type: CBCharacteristicWriteType.withoutResponse)    //Writing the data to the peripheral

    } else {
        print("Not connected")
    }
}


func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    //let indexPath = NSIndexPath(forRow: tag, inSection: 0)
    //let cell = tableView.cellForRow(at: indexPath) as! gpsSettingsCustomCell!
    //print(cell?.cellLabel.text ?? "")

    self.myBluetoothPeripheral[indexPath.row].delegate = self

    manager.stopScan()                          //stop scanning for peripherals
    manager.connect(myBluetoothPeripheral[indexPath.row], options: nil)

    myTableView.deselectRow(at: indexPath, animated: true)
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 60
}

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = gpsSettingsCustomCell(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 60), title: "Hello")
    cell.cellLabel.text = peripheralNames[indexPath.row]
    cell.cellLabel2.text = "Bluetooth Device"
    return cell

}

class BLEDeviceCustomCell: UITableViewCell {
//var cellButton: UIButton!
var cellLabel: UILabel!
var cellLabel2: UILabel!

init(frame: CGRect, title: String) {
    super.init(style: .default, reuseIdentifier: "cell")
    //super.init(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")

    cellLabel = UILabel(frame: CGRect(x: 10, y: 10, width: self.frame.width, height: 20))
    cellLabel.font = UIFont(name: "Titillium-Regular", size: 14.0)
    //cellLabel= UILabel(frame: CGRectMake(self.frame.width - 100, 10, 100.0, 40))
    cellLabel.textColor = UIColor.black
    //cellLabel.font = //set font here

    cellLabel2 = UILabel(frame: CGRect(x: 10, y: 30, width: self.frame.width, height: 20))
    cellLabel2.font = UIFont(name: "Titillium-Regular", size: 14.0)
    cellLabel2.textColor = UIColor.gray
    //cellButton = UIButton(frame: CGRectMake(5, 5, 50, 30))
    //cellButton.setTitle(title, forState: UIControlState.Normal)

    addSubview(cellLabel)
    addSubview(cellLabel2)
    //addSubview(cellButton)
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
}

关于swift - 扫描 BLE 外设并连接到它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53526621/

相关文章:

ios - 提交 App UIApplicationExitsOnSuspend 时出现错误 ITMS-90040

c# - 带有 Xamarin 的 Visual Studio(C#) 中的 OBD II 应用程序

ios - AVAudioSessionPortBluetoothHFP、A2DP、LE有什么区别?

mysql - 安装 Vapor/MySQL 后无法不带参数调用类型 'posix_spawn_files_actions_t' 的初始值设定项

ios - 使用核心图根据圆半径将散点图缩放到 Y 轴

ios - 未显示 UIWebView

android - 通过蓝牙连接到设备,锁定的应用程序

ios - 不要在 iOS 的对话框区域外用点击手势关闭 uialertcontroller 表

swift - 滚动时导航栏标题发生变化

ios - Swift 无法使单元格出队