I have implemented CoreBluetooth for an app based on Apples CoreBluetooth TemperatureSensor example (https://developer.apple.com/library/ios/samplecode/TemperatureSensor/Introduction/Intro.html). It works great searching for devices, populating the results in a tableview, selecting one and connecting. My issue is that I want to keep the connection alive between views across the app.
In my current setup I have a view with a button that takes you to the Bluetooth setup view. The Bluetooth view is presented modally and here I search for BT devices and connects to one of them. As soon as I dismiss the view, the connection is lost, probably due to it not being retained?
Therefore I use a singleton implementation to keep the object (also as in Apples example) hoping to keep the connection alive, but with no luck. I can however retrieve the object from the singleton and call connectPeripheral and re-connect, but from a user perspective, it is not that great that the user has to input the password again after just connecting earlier.
So, how can I keep the bluetooth connection alive between views, e.g. when having a settings view where the BT device is connected, and then use the same connection in the remaining app?
Update: included code
Also worth mentioning is that my class (incl. shared instance) is not only based on the Apple example but also the SerialGATT implementation from HMSoft (which I guess is based on Apples implementation). Here is a link to one place I found on git https://github.com/ezefranca/kit-iot-wearable-ios/blob/master/kit-iot-wearable-ios/SerialGATT.h
So for my singleton I have added the following to SerialGATT.h (also tried with id, not that it made a difference)
+ (SerialGATT *)sharedManager;
and in SerialGATT.m I have
+ (SerialGATT*)sharedManager {
static SerialGATT *_sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_sharedInstance = [[self alloc] init];
});
return _sharedInstance;
}
When using SerialGATT and the singleton in my Bluetooth viewcontroller, I implement the delegate methods of SerialGATT, and then I have the following in viewDidLoad
[[SerialGATT sharedManager] setup];
[[SerialGATT sharedManager] setDiscoveryDelegate:self];
NB! I have renamed discoveryDelegate from the original SerialGATT example, before it was simply named "delegate". discoveryDelegate is the name used in Apples example, not that it matters.
From here on everything works fine in my modal Bluetooth settings view. As stated above, I can search and connect devices. The delegates are being called, all is fine and dandy. However, when I close the modal, the device is disconnected, but I can still find the object in other views when accessing the singleton, and e.g. reconnect. But then again, I would rather keep the connection alive instead of reconnecting and having to input the password again.