问题描述
我需要使用蓝牙连接到我的 iOS 应用程序中的设备才能获取数据。该应用程序是使用 Flutter SDK 开发的,但对于这项特定任务,我决定采用原生方式。 我想从中获取数据的设备是 Raspberry Pi 3,它运行一个 RFCOMM 服务器(或者至少这是文档中所写的)。我没有选择这个协议,我加入项目的时候已经开发好了。
这里是故事的奇怪部分。当我从 iPhone 设置应用程序的蓝牙部分启动扫描时,我能够看到设备并成功连接它;相反,当我从下面看到的代码启动扫描时,我找不到该设备。更重要的是,如果我使用第 3 方应用扫描附近的蓝牙设备(以及检索标识符、RSSI、服务 ID 等数据),则 Raspberry 不会显示在列表中。
这是什么套路?为什么 Apple 让您从“设置”应用而不是从它自己的蓝牙 API(它应该也在“设置”应用中使用)找到设备?
这是我用于扫描的代码:
import CoreBluetooth
...
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate,CBCentralManagerDelegate {
private var centralManager: CBCentralManager?
override func application(
_ application: UIApplication,didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
let controller : FlutterViewController = window?.rootViewController as! FlutterViewController
let bluetoothChannel = FlutterMethodChannel(name: "my.app.bluetooth.channel",binaryMessenger: controller.binaryMessenger)
bluetoothChannel.setMethodCallHandler({
[weak self] (call: FlutterMethodCall,result: @escaping FlutterResult) -> Void in
guard call.method == "scanBluetoothDevices" else {
result(FlutterMethodNotImplemented)
return
}
self?.scanBluetoothDevices(result: result)
})
...
}
...
private func scanBluetoothDevices(result: FlutterResult) {
centralManager = CBCentralManager(delegate: self,queue: nil)
}
...
func centralManager(_ central: CBCentralManager,didDiscover peripheral: CBPeripheral,advertisementData: [String : Any],rssi RSSI: NSNumber) {
print("Peripheral: \(peripheral)")
}
func centralManagerDidUpdateState(_ central: CBCentralManager) {
var consoleMsg = ""
switch (central.state) {
case .poweredOff:
consoleMsg = "BLE is powered off"
case .poweredOn:
consoleMsg = "BLE is powered on"
let options: [String: Any] = [CBCentralManagerScanOptionAllowDuplicatesKey:
NSNumber(value: false)]
centralManager?.scanForPeripherals(withServices: nil,options: options)
...
@unknown default:
consoleMsg = "BLE is in unhandled state"
}
print("\(consoleMsg)")
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)