我找到了cool tutorial来编写应用程序,该应用程序列出了Swift中iOS 10 iPhone上所有可用的蓝牙设备。它可以正常工作。在具有蓝牙功能的iPhone上运行该应用程序,它会在tableView中查找并展示我的Macbook,Linux计算机和随机的“未命名”设备。但是,找不到我的BeatsByDre无线耳机,处于“可发现模式”的Raspberry Pi或插入计算机(运行linux)的简单蓝牙加密狗。
我的问题是:我到底不了解/做错什么?
这是我的表格视图代码:
import CoreBluetooth
import UIKit
class ScanTableViewController: UITableViewController,CBCentralManagerDelegate {
var peripherals:[CBPeripheral] = []
var manager: CBCentralManager? = nil
var parentView:MainViewController? = nil
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
scanBLEDevice()
}
func scanBLEDevice(){
manager?.scanForPeripherals(withServices: nil, options: nil)
DispatchQueue.main.asyncAfter(deadline: .now() + 60.0) {
self.stopScanForBLEDevice()
}
}
func stopScanForBLEDevice(){
manager?.stopScan()
print("scan stopped")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return peripherals.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "scanTableCell", for: indexPath)
let peripheral = peripherals[indexPath.row]
cell.textLabel?.text = peripheral.name
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let peripheral = peripherals[indexPath.row]
manager?.connect(peripheral, options: nil)
}
//CBCentralMaganerDelegate code
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
if (!peripherals.contains(peripheral)){
peripherals.append(peripheral)
}
self.tableView.reloadData()
}
func centralManagerDidUpdateState(_ central: CBCentralManager) {
print(central.state)
}
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
// pass reference to connected peripheral to parentview
parentView?.mainPeripheral = peripheral
peripheral.delegate = parentView
peripheral.discoverServices(nil)
// set manager's delegate view to parent so it can call relevant disconnect methods
manager?.delegate = parentView
parentView?.customiseNavigationBar()
if let navController = self.navigationController{
navController.popViewController(animated: true)
}
print("Connected to "+peripheral.name!)
}
func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
print(error!)
}
基本上,我会寻找外围设备并将其列出到此Table View Controller中。为什么我在列表中看不到无线耳机,却可以在“设置”>“蓝牙”下看到它们?我是否完全误解了什么是外围设备?我已经阅读了Apple文档,然后阅读了一些。我应该在代码中寻找什么?我应该使用信标/ iBeacon吗?
最佳答案
您将只能发现低功耗蓝牙(BLE)设备。
您列出的设备是Bluetooth 2.1设备,Core Bluetooth无法看到它们或不宣传GATT服务。