Ble Peripheral Disconnects When Navigating to Different Viewcontroller

BLE Peripheral disconnects when navigating to different ViewController

Create a Singleton class and add bleManager and peripheral properties there:

class Shared { 
private init(){ }
static let instance = Shared()
var bleManager: BLEManager!
var peripheral: CBPeripheral!
}

And you can access the same instance through different controllers:

Shared.instance.bleManager = BLEManager() 

How to continue BLE activities onto next view controller

Put your BLE related code into a centralized place, e.g. BLEMaganer (better) or AppDelegate (so so). So that controllerA and controllerB can share the same centrolManager instance.

For example, currently you have a property centralManager in controllerA, and implement its delegate in controllerA. You access centralManager by controllerA.centralManager.

Move the centralManager property to AppDelegate, as well other related code. Then you can access centrolManager instance by

(UIApplication.sharedApplication().delegate as! AppDelegate).centralManager.

How to connect peripheral/ BLE device by using identifier?

I want to connect the peripheral by using an identifier. Can I do it?

Short answer:
NO, You can't do it.

Long answer:

Refer apple official document.

There are no provision or method which is used to connect with an
identifier But, Apple has provision to retrieve peripherals by using
the identifier.

Let's discuss some other alternatives

The CBPeripheral does not implement NSCoding. So, it is next to impossible to store BLEPeripheral object into NSUserDefaults OR any other container.

The best solution is to store the properties of CBPeripheral like name or identifier etc.

UserDefaults.standard.set(Device_name, forKey: "Device_name")
UserDefaults.standard.set(Device_Identifier forKey: "Device_Identifier")

By using retrievePeripherals(withIdentifiers:) you can get BLEPeripheral value again. Then you can connect directly using this object

Here is the documentation

retrievePeripherals(withIdentifiers:)

Returns a list of known peripherals by their identifiers.

BLE writeValue to peripheral

You have combined the NSLog statement and the writeValue method into some sort of bizarre mashup.

What you want is

println("Writing value for characteristic \(interestingCharacteristic)")
peripheral.writeValue(dataToWrite, forCharacteristic:interestingCharacteristic, type: CBCharacteristicWriteType.WithResponse)


Related Topics



Leave a reply



Submit