3

I am working on an iPhone app and have implemented CBCentralManager. Also updated plist with background modes, initialized centralmanager with an identifier.

Also have added this code in the 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 have created a central manager in different class and that is 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 peripheral starts advertising, app wakes and fires this notification but doesn't call any CBCentral delegate method. I have also implemented willRestoreState method but thats also not getting card.

Use case: I need to connect the peripheral and send data once its starts advertising, even though app is not being used. Where should I handle connection process when app gets didFinishLaunchingWithOptions call? do i have to initialize the centralManager in the did finishlaunch method?

4

1 回答 1

3

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

A good point to instantiate the manager is in the didFinishLaunchingWithOptions method.

You can test it easy by causing a crash, or by pressing the stop button of xCode while testing, and waiting for a new action triggered by the BLE (a notification from a notifying characteristic for example). It's much faster than waiting few days that the system kills the app for inactivity.

于 2015-08-17T13:20:24.930 回答