Failed to Advertise and Discover BLE with Swift - ios

I am trying to advertise BLE with the following
var perMan: CBPeripheralManager!
let myCustomServiceUUID: CBUUID = CBUUID(string: "109F17E4-EF68-43FC-957D-502BB0EFCF46")
var myService: CBMutableService!
override func viewDidLoad() {
super.viewDidLoad()
perMan = CBPeripheralManager(delegate: self, queue: nil)
myService = CBMutableService(type: myCustomServiceUUID, primary: true)
perMan.addService(myService)
}
// Broadcast when Bluetooth is on
func peripheralManagerDidUpdateState(peripheral: CBPeripheralManager!) {
if peripheral.state == CBPeripheralManagerState.PoweredOn {
// Start advertising over BLE
self.perMan.startAdvertising([CBAdvertisementDataServiceUUIDsKey: [myService.UUID]])
println("Adertising")
} else if peripheral.state == CBPeripheralManagerState.PoweredOff {
self.perMan.stopAdvertising()
}
}
And want to discover the peripheral with
import UIKit
import CoreBluetooth
class SearchViewController: UIViewController, CBCentralManagerDelegate {
var centralManager: CBCentralManager!
#IBOutlet weak var beaconsTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
centralManager = CBCentralManager(delegate: self, queue: nil)
// Listen to BLE of IPhones
let services: NSArray = ["7521105F-8937-48B7-A875-66E6FE21D714"]
centralManager.scanForPeripheralsWithServices(nil, options: nil)
}
// Found IPhone
func centralManager(central: CBCentralManager!, didDiscoverPeripheral peripheral: CBPeripheral!, advertisementData: [NSObject : AnyObject]!, RSSI: NSNumber!) {
println("Hallo:")
println(RSSI)
}
// CBCentralManagerDelegate
func centralManagerDidUpdateState(central: CBCentralManager!) {
}
However the didDiscoverPeripheral method is never called. I am testing on two IPhone5.
Can anyone tell me what I am doing wrong?

Related

Could someone explain what Im doing wrong, in trying to send a text in swift with bluetthooth?

Hello Im kinda new to Swift. Im trying to send a String from a textfield encoded in utf8 via Bluethooth to another iOS device. Here is the code, but I don't understand why it doesn't work.
Peripheral Side:
class ViewController: UIViewController, CBPeripheralDelegate, CBPeripheralManagerDelegate{
#IBOutlet weak var textField : UITextField!
#IBOutlet weak var switchBtn : UISwitch!
var peripheralManager : CBPeripheralManager?
var peripheralDevice : CBPeripheral?
var characteristic : CBMutableCharacteristic?
var data : Data? {
textField.text?.data(using: .utf8) ?? "Yes".data(using: .utf8)
}
override func viewDidLoad() {
super.viewDidLoad()
peripheralManager?.delegate = self
peripheralDevice?.delegate = self
}
func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
switch peripheral.state{
case .poweredOn : setUpPeripheral()
print("e deschisa conexiunea")
case .poweredOff: print("conexiunea e inchisa")
default: print("nu se stie")
}
}
private func setUpPeripheral(){
let transferCharacteristic = CBMutableCharacteristic(type: BTConstants.sampleCharacteristicUUID,
properties: [.notify,.read],
value: data ?? nil,
permissions: [.readable,.writeable])
let transferServer = CBMutableService(type: BTConstants.sampleServiceUUID, primary: true)
transferServer.characteristics = [transferCharacteristic]
peripheralManager?.add(transferServer)
self.characteristic = transferCharacteristic
}
#IBAction func swtichButton(_ sender: Any) {
if switchBtn.isOn{
peripheralManager!.startAdvertising([CBAdvertisementDataServiceUUIDsKey: [BTConstants.sampleServiceUUID]])
}
else{
peripheralManager?.stopAdvertising()
}
}
}
The device which is scanning and receiving the String :
class ViewController: UIViewController, CBCentralManagerDelegate, CBPeripheralDelegate {
#IBOutlet weak var textField : UILabel!
var data : Data?
var cbManager : CBCentralManager!
var peripheralCB : CBPeripheral!
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
override func viewDidLoad() {
super.viewDidLoad()
cbManager = CBCentralManager(delegate: self, queue: nil)
}
func centralManagerDidUpdateState(_ central: CBCentralManager) {
switch central.state{
case .poweredOn :
cbManager.scanForPeripherals(withServices: [BTConstants.sampleServiceUUID]
,options: [CBCentralManagerScanOptionAllowDuplicatesKey : true])
case .poweredOff : self.textField?.text = "poweredOff"
default : self.textField?.text = "Default"
}
}
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
self.cbManager?.stopScan()
guard RSSI.intValue >= -50
else {
os_log("Discovered perhiperal not in expected range, at %d", RSSI.intValue)
return
}
if peripheralCB != peripheral{
peripheralCB = peripheral
}
self.peripheralCB?.delegate = self
self.data = Data()
cbManager?.connect(peripheralCB!, options: nil)
}
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
if self.peripheralCB == peripheral {
os_log("Connected to right peripheral")
}
peripheralCB?.discoverServices([BTConstants.sampleServiceUUID])
}
func setUp(string : String){
self.textField?.text = string
}
func peripheral(_ : CBPeripheral, didUpdateValueFor : CBCharacteristic, error: Error?) {
if error != nil {
os_log("this is sparta")
}
guard let characteristicData = didUpdateValueFor.value,
let stringFromData = String(data: characteristicData, encoding: .utf8) else { return }
setUp(string: String(data: characteristicData, encoding: .utf8) ?? "Doesnt work")
}
}

BLE Connection between iPhone and iPad with JustWorks bonding

I'm currently working on a app that needs to send data from a iPhone to a iPad. I've been able to find the devices and connecting them by using both the CentralManager and PeriphiralManager. However right now it's showing me a message to asking to pair every single time. But when I press the "NO" option it will still bond by using JustWorks (at least it seems because when I go to bluetooth in settings it will just say "iPad" and I can't see information about the device other than that and it disappears from the list completely when I disconnect).
I was wondering how I could make sure the popup asking for pairing doesn't show up at all. I read somewhere to disable encryption on the Peripheral however I'm not sure how to do this when the iPad for instance is the Peripheral. The code I'm using right now looks as follows (this is the first time I'm working with corebluetooth and I'm currently still messing around with it and trying to get a grasp of how it works).
import UIKit
import CoreBluetooth
import CoreLocation
class ViewController: UIViewController {
#IBOutlet weak var receiveLabel: UILabel!
#IBOutlet weak var sendButton: UIButton!
var centralManager: CBCentralManager!
var peripheralManager: CBPeripheralManager!
var peripherals: [CBPeripheral] = []
var keepScanning: Bool = false
private var timerScanInterval: TimeInterval = 5
static let SERVICE_UUID = CBUUID(string: "4DF91029-B356-463E-9F48-BAB077BF3EF5")
static let RX_UUID = CBUUID(string: "3B66D024-2336-4F22-A980-8095F4898C42")
static let RX_PROPERTIES: CBCharacteristicProperties = .write
static let RX_PERMISSIONS: CBAttributePermissions = .writeable
override func viewDidLoad() {
super.viewDidLoad()
centralManager = CBCentralManager(delegate: self, queue: DispatchQueue.main)
peripheralManager = CBPeripheralManager(delegate: self, queue: nil)
}
}
extension ViewController {
#IBAction func sendMessage(_ sender: UIButton) {
for per in peripherals {
centralManager.connect(per, options: nil)
}
}
func updateAdvertisingData() {
if peripheralManager.isAdvertising {
peripheralManager.stopAdvertising()
}
peripheralManager.startAdvertising([CBAdvertisementDataServiceUUIDsKey: [ViewController.SERVICE_UUID], CBAdvertisementDataLocalNameKey: "Test"])
}
func initService() {
let serialService = CBMutableService(type: ViewController.SERVICE_UUID, primary: true)
let rx = CBMutableCharacteristic(type: ViewController.RX_UUID, properties: ViewController.RX_PROPERTIES, value: nil, permissions: ViewController.RX_PERMISSIONS)
serialService.characteristics = [rx]
peripheralManager.add(serialService)
}
}
extension ViewController: CBCentralManagerDelegate {
func centralManagerDidUpdateState(_ central: CBCentralManager) {
switch central.state {
case .poweredOn:
centralManager.scanForPeripherals(withServices: [ViewController.SERVICE_UUID], options: [CBCentralManagerScanOptionAllowDuplicatesKey: true])
break
default: break
}
}
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
peripheral.discoverServices(nil)
peripherals.append(peripheral)
}
}
extension ViewController: CBPeripheralDelegate, CBPeripheralManagerDelegate {
func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
if peripheral.state == .poweredOn {
initService()
updateAdvertisingData()
}
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
for service in peripheral.services! {
peripheral.discoverCharacteristics(nil, for: service)
}
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
for characteristic in service.characteristics! {
let characteristic = characteristic as CBCharacteristic
let message = "TestMessage".data(using: .utf8)
peripheral.writeValue(message!, for: characteristic, type: CBCharacteristicWriteType.withResponse)
}
}
func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveWrite requests: [CBATTRequest]) {
for request in requests {
if let value = request.value {
let messageText = String(data: value, encoding: String.Encoding.utf8)
receiveLabel.text = messageText
}
self.peripheralManager.respond(to: request, withResult: .success)
}
}
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
peripheral.delegate = self
peripheral.discoverServices(nil)
}
}
Even though you only searched for peripherals that are advertising your specific service, when you discover a peripheral, you call
peripheral.discoverServices(nil)
This will discover all services on the discovered peripheral (which is another iOS device), not just your specific service.
Then, for each service you discover all characteristics and for each characteristic you discover you write to it with
let message = "TestMessage".data(using: .utf8)
peripheral.writeValue(message!, for: characteristic, type: CBCharacteristicWriteType.withResponse)
Since you have discovered all characteristics for all services on the device and then attempt to write to each one, if any of those characteristics require encryption you will trigger the pairing dialog. When you cancel the pairing dialog, that particular write will fail, but your app will keep on working (which is why you see the connection in settings).
You should refine your code so that it only discovers the specific service you are interested in and only attempts to write to your characteristic. This will prevent the pairing dialog from being triggered as your characteristic does not require encryption.

Connecting bluetooth between iPad and iPhone

I'm currently trying to make 2 iOS devices connect with each other so I can send gps locations between the two. Right now I'm using corebluetooth to achieve this.
What I did so far is I created 2 separate projects, one being the receiver one being the sender. I followed some instructions from apple itself to broadcast the iPad. However it doesn't seem to be found by the project that is trying to search for Bluetooth devices. I ran both apps on separate physical devices with bluetooth turned on. Below the code that I've used (keep in mind this is some quick code I wrote to try and see if I can actually find the device.) This is also the first time I work with bluetooth so it's a learning curve for sure.
FYI: I'm planning on using the GATT protocol. I'm also wondering if it can be done without a pairing handshake in the way that I get a popup to accept the connection. I would like the receiver to automatically receive and broadcasted signal and start obtaining the data that is being sent without additional steps needed. Or would I need something like Multipeer Connectivity Framework for this?
Receiver
import UIKit
import CoreBluetooth
import CoreLocation
class ViewController: UIViewController {
private let uuidBeacon = "A26962FC-F9DD-4251-B339-A25B3E808213"
var peripheral: CBPeripheralManager!
var peripheralData: NSMutableDictionary!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
peripheral = CBPeripheralManager(delegate: self, queue: nil)
}
override func viewDidAppear(_ animated: Bool) {
guard let region = createBeaconRegion() else { return }
advertiseDevice(region: region)
}
private func createBeaconRegion() -> CLBeaconRegion? {
let proximityUUID = UUID(uuidString: uuidBeacon)
let major : CLBeaconMajorValue = 100
let minor : CLBeaconMinorValue = 1
let beaconID = "com.example.myDeviceRegion"
return CLBeaconRegion(proximityUUID: proximityUUID!,
major: major, minor: minor, identifier: beaconID)
}
func advertiseDevice(region : CLBeaconRegion) {
peripheralData = region.peripheralData(withMeasuredPower: nil)
}
}
extension ViewController: CBPeripheralManagerDelegate {
func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
switch peripheral.state {
case .poweredOn:
peripheral.startAdvertising(((peripheralData as NSDictionary) as! [String : Any]))
case .poweredOff:
break
// peripheral.stopAdvertising()
default:
break
}
}
}
Broadcaster
import UIKit
import CoreBluetooth
import CoreLocation
class ViewController: UIViewController {
var centralManager: CBCentralManager!
var sensorTag: CBPeripheral?
var keepScanning: Bool = false
private var timerScanInterval: TimeInterval = 5
override func viewDidLoad() {
super.viewDidLoad()
centralManager = CBCentralManager(delegate: self, queue: nil)
}
}
extension ViewController: CBCentralManagerDelegate {
func centralManagerDidUpdateState(_ central: CBCentralManager) {
switch central.state {
case .poweredOn:
keepScanning = true
_ = Timer(timeInterval: timerScanInterval, target: self, selector: #selector(pauseScan), userInfo: nil, repeats: false)
centralManager.scanForPeripherals(withServices: nil, options: nil)
break
case .poweredOff:
break
case .unsupported:
break
case .unauthorized:
break
case .resetting:
break
case .unknown:
break
}
}
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
peripheral.discoverServices(nil)
if let peripheralName = advertisementData[CBAdvertisementDataLocalNameKey] as? String {
print(peripheralName)
}
}
#objc private func pauseScan() {
centralManager.stopScan()
_ = Timer(timeInterval: 2, target: self, selector: #selector(resumeScan), userInfo: nil, repeats: false)
}
#objc private func resumeScan() {
if keepScanning {
centralManager.scanForPeripherals(withServices: nil, options: nil)
_ = Timer(timeInterval: timerScanInterval, target: self, selector: #selector(pauseScan), userInfo: nil, repeats: false)
}
}
}
extension ViewController: CBPeripheralDelegate {
}

CoreBluetooth Functions not working from Singleton

So I currently got a bluetooth connection setup between a iPad and iPhone. I've created my testcode in the ViewController and everything works fine. Now I moved it to 2 manager classes one for the CBCentralManager and one for the CBPeripheralManager above those to classes I made a BluetoothManager which is a singleton class and holds some information regarding currently connected devices.
However when doing this I'm facing a problem it seems like the centralManager.connect() call doesn't actually work. I debugged my entire code and after that line nothing seems to happen and I can't seem to figure out why this is or where I'm actually going wrong.
The CentralManager class
import Foundation
import CoreBluetooth
class CentralManager: NSObject {
private var centralManager: CBCentralManager!
var peripherals: [CBPeripheral] = []
override init() {
super.init()
centralManager = CBCentralManager(delegate: self, queue: DispatchQueue.main)
}
}
// MARK: - CBCentralManager Delegate Methods
extension CentralManager: CBCentralManagerDelegate {
func centralManagerDidUpdateState(_ central: CBCentralManager) {
switch central.state {
case .poweredOn:
centralManager.scanForPeripherals(withServices: [BLEConstants.serviceUUID], options: [CBCentralManagerScanOptionAllowDuplicatesKey: true])
default:
break
}
}
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
if !peripherals.contains(peripheral) {
peripheral.delegate = self
peripherals.append(peripheral)
centralManager.connect(peripheral, options: nil)
}
}
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
peripheral.discoverServices([BLEConstants.serviceUUID])
}
func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
guard let peripheralIndex = peripherals.index(of: peripheral), BluetoothManager.shared.deviceCharacteristic[peripheral] != nil else { return }
peripherals.remove(at: peripheralIndex)
BluetoothManager.shared.deviceCharacteristic.removeValue(forKey: peripheral)
}
}
// MARK: - CBPeripheral Delegate Methods
extension CentralManager: CBPeripheralDelegate {
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
for service in peripheral.services! {
if service.uuid == BLEConstants.serviceUUID {
peripheral.discoverCharacteristics(nil, for: service)
}
}
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
for characteristic in service.characteristics! {
let characteristic = characteristic as CBCharacteristic
if BluetoothManager.shared.deviceCharacteristic[peripheral] == nil {
BluetoothManager.shared.deviceCharacteristic[peripheral] = characteristic
}
}
}
func peripheral(_ peripheral: CBPeripheral, didModifyServices invalidatedServices: [CBService]) {
}
}
The PeripheralManager class
class PeripheralManager: NSObject {
private var peripheralManager: CBPeripheralManager!
override init() {
super.init()
peripheralManager = CBPeripheralManager(delegate: self, queue: nil)
}
}
// MARK: - Manage Methods
extension PeripheralManager {
func updateAdvertising() {
guard !peripheralManager.isAdvertising else { peripheralManager.stopAdvertising(); return }
let advertisingData: [String: Any] = [CBAdvertisementDataServiceUUIDsKey: BLEConstants.serviceUUID,
CBAdvertisementDataLocalNameKey: BLEConstants.bleAdvertisementKey]
peripheralManager.startAdvertising(advertisingData)
}
func initializeService() {
let service = CBMutableService(type: BLEConstants.serviceUUID, primary: true)
let characteristic = CBMutableCharacteristic(type: BLEConstants.charUUID, properties: BLEConstants.charProperties, value: nil, permissions: BLEConstants.charPermissions)
service.characteristics = [characteristic]
peripheralManager.add(service)
}
}
// MARK: - CBPeripheralManager Delegate Methods
extension PeripheralManager: CBPeripheralManagerDelegate {
func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
if peripheral.state == .poweredOn {
initializeService()
updateAdvertising()
}
}
func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveWrite requests: [CBATTRequest]) {
for request in requests {
if let value = request.value {
let messageText = String(data: value, encoding: String.Encoding.utf8)
print(messageText ?? "")
}
self.peripheralManager.respond(to: request, withResult: .success)
}
}
}
The BluetoothManager class
class BluetoothManager {
static let shared = BluetoothManager()
private var centralManager: CentralManager!
private var peripheralManager: PeripheralManager!
var deviceCharacteristic: [CBPeripheral: CBCharacteristic] = [:]
var connectedPeripherals: [CBPeripheral] { return centralManager.peripherals }
func setup() {
centralManager = CentralManager()
peripheralManager = PeripheralManager()
}
}
and then in my ViewController didLoad I'm calling BluetoothManager.shared.setup()
Does anyone know why the devices don't seem to connect with eachother or maybe the delegate functions after that just don't get called?
The process starts when the static shared variable is initialized with BluetoothManager(). I am not sure when this happens in Swift, it is either at the very start of the program, or when you use BluetoothManager.setup for the first time.
Initialization of the variable calls the init() method of the BluetoothManager. This will instantiate a CentralManager, and its init() method will be called. This will instantiate a CBCentralManager, which will start the Bluetooth process.
Then you call setup(), which will instantiate a new CentralManager, with its own CBCentralManager. I can imagine something goes wrong with two CBCentralManager.
To solve it, don't use setup(), but initialize the variables in init() instead.
To debug this kind of situation, put breakpoints in all init() methods. Create destructors, and put breakpoints in those as well. Technically, you need destructors anyways, because you need to remove yourself as delegate from the CBCentralManager object.
Note also that you only call scanForPeripherals from centralManagerDidUpdateState. The CBCentralManager can already be in poweredOn state when it starts, this can happen when another app is using Bluetooth at the same time - or when your first CBCentralManager object has already started it. In that case, centralManagerDidUpdateState will never be called.
Are you sure your Singleton is correctly initialized?
Try this:
import Foundation
private let singleton = Singleton()
class Singleton {
static let sharedInstance : Singleton = {
return singleton
}()
let cnetralManager = = CBCentralManager(delegate: self, queue: DispatchQueue.main)
}

Getting BLE (dynamic) data on another screen - iOS swift

I'm brand new to iOS + BLE development. I'm trying to do something very basic - connecting a BLE device to an app. There are two screens to this app.
First screen is where it detects BLE status "ble_Status" label - if BLE is ON/OFF on
the device. If the device is receiving advertisement signals from
BLE chip, then connect to BLE chip. Currently, "Connect" and "Skip Page" navigate to second screen as a show Action Triggered Segue.
Second screen has one label "amt_consumed" - this is where the ble characteristic data needs to be displayed.
Second screen is where the characteristic data needs to be displayed
on "amt_consumed" label.
I made a new cocoa class and use prepareforsegue to pass data to the next screen. It works but only shows one value. The value from ble is dynamic and changes accordingly on the first screen but on the second screen, amt_consumed shows the value at the moment the segue is triggered. How do I keep this value updating constantly?
Here's the code:
ViewController.swift
import UIKit
import CoreBluetooth
import Foundation
//Define BLE UUID Variables
var bleServiceUUID: CBUUID!
var bleCharUUID: CBUUID!
class ViewController: UIViewController, CBCentralManagerDelegate, CBPeripheralDelegate {
//Define BLE Manager/Peripheral Variables
var cManager : CBCentralManager!
var blePeripheral : CBPeripheral!
//Define BLE Outlets
#IBOutlet weak var ble_Status: UILabel!
#IBOutlet weak var amt_consumed: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//------->BLE<--------//
bleServiceUUID = CBUUID(string:"FFF0")
bleCharUUID = CBUUID(string:"FFF1")
cManager = CBCentralManager(delegate: self, queue: nil)
//------->BLE END<--------//
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//-------->BLE CODE START<-------//
//Check HW for BLE
func centralManagerDidUpdateState(central: CBCentralManager!) {
self.ble_Status.text = "Searching for BLE Devices"
switch (central.state) {
case .PoweredOff:
self.ble_Status.text = "BLE Off"
case .PoweredOn:
self.ble_Status.text = "BLE ON and searching..."
central.scanForPeripheralsWithServices(nil, options: nil)
default:
self.ble_Status.text = "Cannot find"
}
}
func centralManager(central: CBCentralManager!, didDiscoverPeripheral peripheral: CBPeripheral!, advertisementData: (NSDictionary), RSSI: NSNumber!) {
if peripheral.name == "Nishant's Flow Bottle" {
println("Discovered: \(peripheral.name)")
ble_Status.text = "Discovered: \(peripheral.name)"
self.blePeripheral = peripheral
cManager.stopScan()
self.cManager.connectPeripheral(peripheral, options: nil)
}
else {
central.scanForPeripheralsWithServices(nil, options: nil)
}
}
// Check out the discovered peripherals to find Sensor Tag
func centralManager(central: CBCentralManager!,didConnectPeripheral peripheral: CBPeripheral!)
{
peripheral.delegate = self
peripheral.discoverServices([CBUUID(string: "0F37491A-AA8E-51B4-0252-F5F0857134D9")])
self.ble_Status.text = "Connected to \(peripheral.name)"
//---discover the specified service---
var services = [bleServiceUUID]
peripheral.discoverServices(services)
}
// If disconnected, start searching again
func centralManager(central: CBCentralManager!, didDisconnectPeripheral peripheral: CBPeripheral!, error: NSError!) {
self.ble_Status.text = "Disconnected"
central.scanForPeripheralsWithServices(nil, options: nil)
}
//---fired when services are discovered---
func peripheral(peripheral: CBPeripheral!,
didDiscoverServices error: NSError!) {
for service in peripheral.services {
println(
"P: \(peripheral.name) - Discovered service S:'\(service.UUID)'")
if service.UUID == bleServiceUUID {
//---discover the specified characteristic of the service---
var characteristics =
[bleCharUUID]
//---discover the characteristics of the service---
peripheral.discoverCharacteristics(
characteristics, forService: service as CBService)
}
}
}
func peripheral(peripheral: CBPeripheral!,
didDiscoverCharacteristicsForService service: CBService!,
error: NSError!) {
// 0x01 data byte to enable sensor
var enableValue = NSInteger(1)
for characteristic in service.characteristics {
//---look for the characteristic that allows you to subscribe to---
let thischaracteristic = characteristic as CBCharacteristic
if thischaracteristic.UUID == bleCharUUID {
//---subscribe to the characteristic---
self.blePeripheral.setNotifyValue(true, forCharacteristic: thischaracteristic)
}
blePeripheral.readValueForCharacteristic(thischaracteristic)
}
}
func peripheral(peripheral: CBPeripheral!, didUpdateValueForCharacteristic characteristic: CBCharacteristic!, error: NSError!) {
if var data :NSData = characteristic.value {
output("Data", data: characteristic.value)
}
}
func output(description: String, data: AnyObject){
println("\(description): \(data)")
amt_consumed.text = "\(data)"
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if (segue.identifier == "btnSubmitSegue") {
var svc = segue.destinationViewController as NextScreen;
svc.dataPassed = CharReadData.text
}
}
}
Nextscreen.swift
import UIKit
class NextScreen: UIViewController {
#IBOutlet weak var amt_consumed: UILabel!
var dataPassed: String!
override func viewDidLoad() {
super.viewDidLoad()
amt_consumed.text = dataPassed
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}

Resources