BLE-Calls didFinishLaunchingWithOptions save and restore state but does not call any delegate method for CBCentral

I am working on an iPhone app and have implemented CBCentralManager

. Also updated plist with background modes, initialized by centralmanager with id.

Also added this code to 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)

            }
        }
}

      

I created a central manager in another class and it is a singleton.

    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"])
}

      

If I don't use my app for a day or two, and then the peripheral starts advertising, the app wakes up and fires that notification, but doesn't call any CBCentral delegate method. I also implemented the willRestoreState method, but also not getting the map.

Use case. I need to connect a peripheral and send data after it starts advertising, even if the app is not in use. Where should I handle the connection process when the application receives didFinishLaunchingWithOptions call? do i need to initialize centralManager in didlawnLunch method?

+3


source to share


1 answer


The central manager must be initialized immediately to handle the call to the delegate. The delegate method is called after the CBPeripheralManager is created, and the delegate is passed to the init method. If the manager ID matches the pending session, the state will be restored.

A good point to create a manager instance is the didFinishLaunchingWithOptions

.



You can easily test it by causing a crash, or by pressing the xCode stop button during testing and waiting for a new action triggered by BLE (like a notification from a notification token). It's much faster than waiting days for the system to kill an app for inactivity.

+3


source







All Articles