我正在尝试在后台监听我的蓝牙设备,但好像没有任何反应。我尝试按照这里的指南进行操作,并对其进行了 SwiftUI 的修改。
我启用了 bluetooth-central
后台模式。
我选择加入状态保存和恢复。
let options = [CBCentralManagerOptionRestoreIdentifierKey : "myCentralManagerIdentifier"]
centralManager = CBCentralManager(delegate: self, queue: nil, options: options)
我添加了恢复代理方法。当我再次运行应用程序时,该方法会被调用。
func centralManager(_ central: CBCentralManager, willRestoreState dict: [String : Any]) {
guard let peripherals = dict[CBCentralManagerRestoredStatePeripheralsKey] as? [CBPeripheral] else {
return
}
for peripheral in peripherals {
// ...
}
}
启动选项的步骤对我似乎不起作用。对我来说,launchOptions
字典始终为 nil
。
import SwiftUI
import UIKit
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
guard let options = launchOptions else {
return true
}
let centralManagerIdentifiers = options[UIApplication.LaunchOptionsKey.bluetoothCentrals]
return true
}
}
@main
struct MyApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
WindowGroup {
ContentView()
}
}
}