swift - 状态保存和恢复 BLE- 调用 didFinishLaunchingWithOptions 但不为 CBCentral 调用任何委托(delegate)方法

标签 swift cbcentralmanager ios-bluetooth

我正在开发 iPhone 应用程序并已实现 CBCentralManager。还使用后台模式更新了 plist,使用标识符初始化了 centralmanager。

还在didFinishLaunchingWithOptions中添加了这段代码

if var centralManagerIdentifiers: NSArray = launchOptions?    [UIApplicationLaunchOptionsBluetoothCentralsKey] as? NSArray {
    // Awake as Bluetooth Central
    // No further logic here, will be handled by centralManager willRestoreState

    for identifier in  centralManagerIdentifiers {
        if identifier as NSString == "centralManager"{
            var notification = UILocalNotification()
            notification.alertBody = String(centralManagerIdentifiers.count) 
            notification.alertAction = "open" 
            notification.fireDate =  NSDate()
            notification.soundName = UILocalNotificationDefaultSoundName 
            UIApplication.sharedApplication().scheduleLocalNotification(notification)

            }
        }
}

我在不同的类中创建了一个中央管理器,它是单例的。

    class var sharedInstance: BLEManager {
    struct Singleton {
        static let instance = BLEManager()
    }

    return Singleton.instance
}


override init() {
    super.init()
    let centralQueue = dispatch_queue_create(“centralManager_queue”, DISPATCH_QUEUE_SERIAL)
    centralManager = CBCentralManager(delegate: self, queue: centralQueue, options: [CBCentralManagerOptionRestoreIdentifierKey : "centralManager"])
}

如果我一两天不使用我的应用程序,然后外围设备开始广告,应用程序会唤醒并触发此通知,但不会调用任何 CBCentral 委托(delegate)方法。我也实现了 willRestoreState 方法,但那也没有得到卡片。

用例:我需要连接外围设备并在其开始广告后发送数据,即使应用程序未被使用。 当应用程序收到 didFinishLaunchingWithOptions 调用时,我应该在哪里处理连接过程?我必须在 did finishlaunch 方法中初始化 centralManager 吗?

最佳答案

必须立即初始化中央管理器以处理委托(delegate)调用。一旦创建 CBPeripheralManager 并将委托(delegate)传递给 init 方法,就会调用委托(delegate)方法。如果管理器的标识符与挂起的 session 匹配,则状态将被恢复。

didFinishLaunchingWithOptions 方法是实例化管理器的一个好点。

您可以通过导致崩溃或在测试时按下 xCode 的停止按钮并等待 BLE 触发的新操作(例如来自通知特性的通知)来轻松测试它。这比等待几天系统杀死不活动的应用要快得多。

关于swift - 状态保存和恢复 BLE- 调用 didFinishLaunchingWithOptions 但不为 CBCentral 调用任何委托(delegate)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30942256/

相关文章:

swift - 了解结构初始化器是否包含私有(private)属性

swift - 自定义 tableviewcell 中的 PieChartView

swift - 无法保存到核心数据中

ios - 蓝牙 Controller 列出多个版本的设备 - Swift 3.1

bluetooth - Unity 可以从 iOS 上的蓝牙键盘读取输入吗?

bluetooth-lowenergy - 使用来自 Android 或 iOS 的 Microhip 的 MLDP 数据流

ios - Wkwebview 对 YouTube 链接没有反应

ios - 更新CentralManagers外围设备的服务列表

ios - 如何在 iOS 中连续搜索蓝牙外设

ios - 如何知道蓝牙设备连接/断开状态回调到后台运行的iOS应用程序?