iOS蓝牙无法发现设备



我正在尝试创建一个扫描外围BLE设备的应用程序。我用的是BLE Mini,我可以看到它在使用LightBlue和RedBear的iPhone应用程序。我已经确认开机扫描,但是当我运行程序时,没有发现BLE设备。我看过很多在iOS中实现Corebluetooth的例子,似乎我拥有所有所需的功能。我哪里做错了?谢谢你的帮助。

//  BlueToothVC.swift
import UIKit
import CoreBluetooth
class BlueToothVC: UIViewController, UITableViewDataSource, UITableViewDelegate, CBCentralManagerDelegate 
{
    @IBOutlet weak var tableView: UITableView!
    var centralManager: CBCentralManager!
    var peripherals: Array<CBPeripheral> = Array<CBPeripheral>()
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.delegate = self
        tableView.dataSource = self
        centralManager = CBCentralManager(delegate: self, queue: DispatchQueue.main)

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false
        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    //CoreBluetooth methods
    func centralManagerDidUpdateState(_ central: CBCentralManager)
    {
        if (central.state == CBManagerState.poweredOn)
        {
            print("scanning")
            self.centralManager?.scanForPeripherals(withServices: nil, options: nil)
        }
        else
        {
            // do something like alert the user that ble is not on
        }
    }
    private func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber)
    {
        peripherals.append(peripheral)
        tableView.reloadData()
        print("saw something")
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return peripherals.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = self.tableView.dequeueReusableCell(withIdentifier: "BTCell")! as! BTCell
        let peripheral = peripherals[indexPath.row]
        cell.label.text = peripheral.name
        return cell
    }
    @IBAction func touchCancel(_ sender: AnyObject) {
        self.navigationController?.popViewController(animated: true)
    }
}

您的didDiscoverPeripheral委托方法不正确。

我注意到你把它改成了private;这可能是因为Xcode给了你一个错误,这个函数"几乎匹配了另一个方法的签名",并建议将其设置为私有。这样做可以从外部类隐藏该方法并消除错误,但这意味着您没有实现didDiscoverPeripheral委托方法。

需要_central:之前的函数签名

private func centralManager(_ central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber)
{
    peripherals.append(peripheral)
    tableView.reloadData()
    print("saw something")
}

最新更新