Thread 1 : signal SIGABRT unrecognized selector - ios

I am currently creating a Bluetooth chat application with Xcode 8 that allows two devices to connect to each other via Bluetooth and send and receive messages to one another. Below is the code for this.
import UIKit
import CoreBluetooth
class ViewController: UIViewController, CBPeripheralManagerDelegate, CBCentralManagerDelegate, CBPeripheralDelegate {
let messageUUID = CBUUID(string: "053D6600-821E-46A7-AC25-43A81D948E8B")
let inputUUID = CBUUID(string: "49A79D26-5323-4374-81EA-29B099AF85C8")
let otherUUID = CBUUID(string: "053D6600-821E-46A7-AC25-43A81D948E87")
var peripheralManager: CBPeripheralManager!
var characteritic: CBMutableCharacteristic!
var getDataPeripheralCharacteristic: CBMutableCharacteristic!
var service: CBMutableService!
var outputData:String = ""
var centralManager: CBCentralManager!
var connectingPeripheral: CBPeripheral?
var centralWriteCharacteristic: CBCharacteristic!
#IBOutlet weak var inputLabel: UITextField!
#IBOutlet weak var outputLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func centralMode(sender: AnyObject) {
centralManager = CBCentralManager(delegate: self, queue: nil)
peripheralManager = nil
}
#IBAction func peripheralMode(sender: AnyObject) {
peripheralManager = CBPeripheralManager(delegate: self, queue: nil)
centralManager = nil
}
func peripheralManager(peripheral: CBPeripheralManager, didAddService service: CBService, error: NSError?) {
peripheral.stopAdvertising()
let identifier = Bundle.main.bundleIdentifier!
let manufacturerData = identifier.data(using: String.Encoding.utf8, allowLossyConversion: false)
let dataToBeAdvertised:[String: Any] = [
CBAdvertisementDataLocalNameKey : "Sample peripheral",
CBAdvertisementDataManufacturerDataKey : manufacturerData as Any,
CBAdvertisementDataServiceUUIDsKey : [messageUUID, inputUUID],
]
peripheralManager.startAdvertising(dataToBeAdvertised)
}
#IBAction func sendData(_ sender: UIButton) {
if (peripheralManager != nil) {
let passed = peripheralManager.updateValue(inputLabel.text!.data(using: String.Encoding.utf8)!, for: characteritic!, onSubscribedCentrals: nil)
if passed == false {
print("error couldn't send data")
}
}
if (centralManager != nil) {
if (connectingPeripheral != nil) {
connectingPeripheral?.writeValue(inputLabel.text!.data(using: String.Encoding.utf8)!, for: centralWriteCharacteristic, type: CBCharacteristicWriteType.withResponse)
}
}
}
func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
if (peripheral.state == .poweredOn) {
characteritic = CBMutableCharacteristic(type: messageUUID, properties: CBCharacteristicProperties.notify, value: nil, permissions: CBAttributePermissions.readable)
getDataPeripheralCharacteristic = CBMutableCharacteristic(type: inputUUID, properties:
CBCharacteristicProperties.write, value: nil, permissions: CBAttributePermissions.writeable)
service = CBMutableService(type: otherUUID, primary: true)
service.characteristics = [characteritic!, getDataPeripheralCharacteristic!]
peripheralManager!.add(service)
}
}
func peripheralManager(peripheral: CBPeripheralManager, didReceiveWriteRequests requests: [CBATTRequest]) {
for request in requests {
if (request.characteristic.uuid.uuidString == inputUUID.uuidString) {
outputData = String(data: request.value!, encoding: String.Encoding.utf8)!
outputLabel.text = outputData
}
}
}
func peripheralManager(peripheral: CBPeripheralManager, didReceiveReadRequest request: CBATTRequest) {
}
func centralManagerDidUpdateState(_ central: CBCentralManager) {
if central.state == .poweredOn {
centralManager.scanForPeripherals(withServices: nil, options: nil)
//search for peripheral device
}
}
//when peripheral is discovered, this method is called
private func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) {
self.centralManager.stopScan();
self.connectingPeripheral = peripheral;
peripheral.delegate = self;
centralManager.connect(peripheral, options: nil)
}
//if connection request from central is succesfull, this method is called
func centralManager(central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) {
peripheral.delegate = self;
peripheral.discoverServices(nil)
}
//if central discovers services, this method is called
private func peripheral(peripheral: CBPeripheral, didDiscoverServices error: NSError?) {
for service: CBService in peripheral.services! {
peripheral.discoverCharacteristics(nil, for: service)
}
}
private func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError?) {
if (service.uuid.uuidString == otherUUID.uuidString) {
guard let characteristics = service.characteristics else {
return
}
for characteristic in characteristics {
if characteristic.uuid.uuidString == messageUUID.uuidString {
peripheral.setNotifyValue(true, for: characteristic)
} else if characteristic.uuid.uuidString == inputUUID.uuidString {
centralWriteCharacteristic = characteristic
}
}
}
}
private func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) {
if error != nil {
print("Error reading characteristics");
}
if (characteristic.uuid == messageUUID) {
outputData = String(data: characteristic.value!, encoding: String.Encoding.utf8)!
print(outputData)
outputLabel.text = outputData
}
}
}
The Thread 1 signal SIGABRT error is produced when I click either central mode or peripheral mode but not when I click send data. I have done some research online and the general solution to this error is to check the connections for the buttons and make sure there is only one connection and it is the correct one. I have done this but it still has not fixed the error. Below are images of the connections for these buttons.
central mode button
peripheral mode button

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

have to initiate a BLE peripheral every time i use it in Swift

with CBCentralManager i succesully scan multiple BLE UART devices and connect to them, de devices are stored in the array periphirals[], but when i want to send data to them one by one, only the last one connected i can send succesfully send data to, i solved it by calling blePeripheral?.discoverServices([ParticlePeripheral.BLEService_UUID])before writing data again, but i think this is not the right solution, can someone explain what i am doing wrong?
Below the code i use, the scanning and connecting start by didload
and startCyclus starts the first device, after the data recieved "didUpdateValueFor" is entered , getting the data and direct send data to the next peripheral
import Foundation
import UIKit
import CoreBluetooth
var txCharacteristic : CBCharacteristic?
var rxCharacteristic : CBCharacteristic?
var blePeripheral : CBPeripheral?
var characteristicASCIIValue = NSString()
var Running = false
var currentNode = 0;
var updateService = false
var maxNodes = Int()
class ViewController : UIViewController, CBCentralManagerDelegate, CBPeripheralDelegate, UITableViewDelegate{
//Data
var centralManager : CBCentralManager!
var RSSIs = [NSNumber]()
var data = NSMutableData()
var peripherals: [CBPeripheral] = []
var characteristicValue = [CBUUID: NSData]()
var timer = Timer()
var characteristics = [String : CBCharacteristic]()
var teller = 0
//UI
#IBOutlet weak var baseTableView: UITableView!
#IBOutlet weak var refreshButton: UIBarButtonItem!
#IBAction func naarRun(_ sender: Any) {
print("naarRun")
self.performSegue(withIdentifier:"naarRunView" , sender: self)
}
override func viewDidLoad() {
super.viewDidLoad()
centralManager = CBCentralManager(delegate: self, queue: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
if (segue.identifier == "naarRunView") {
let vc = segue.destination as! ViewRun
vc.peripherals = peripherals
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
//print("View Cleared")
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
print("Stop Scanning")
centralManager?.stopScan()
}
/*Okay, now that we have our CBCentalManager up and running, it's time to start searching for devices. You can do this by calling the "scanForPeripherals" method.*/
func startScan() {
peripherals = []
print("Now Scanning...")
self.timer.invalidate()
centralManager?.scanForPeripherals(withServices: [ParticlePeripheral.BLEService_UUID] , options: [CBCentralManagerScanOptionAllowDuplicatesKey:false])
Timer.scheduledTimer(withTimeInterval: 3, repeats: false) {_ in
self.cancelScan()
self.connectToAllDevices()
}
}
/*We also need to stop scanning at some point so we'll also create a function that calls "stopScan"*/
func cancelScan() {
self.centralManager?.stopScan()
print("Scan Stopped")
print("Number of Peripherals Found: \(peripherals.count)")
}
func disconnectFromDevice () {
if blePeripheral != nil {
// We have a connection to the device but we are not subscribed to the Transfer Characteristic for some reason.
// Therefore, we will just disconnect from the peripheral
centralManager?.cancelPeripheralConnection(blePeripheral!)
}
}
func restoreCentralManager() {
//Restores Central Manager delegate if something went wrong
centralManager?.delegate = self
}
/*
Called when the central manager discovers a peripheral while scanning. Also, once peripheral is connected, cancel scanning.
*/
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral,advertisementData: [String : Any], rssi RSSI: NSNumber) {
blePeripheral = peripheral
teller+=1
self.peripherals.append(peripheral)
self.RSSIs.append(RSSI)
peripheral.delegate = self
//self.baseTableView.reloadData()
//if blePeripheral == nil {
print("Found new pheripheral devices with services")
print("Peripheral name: \(String(describing: peripheral.name))")
print("**********************************")
print ("Advertisement Data : \(advertisementData)")
//}
}
//Peripheral Connections: Connecting, Connected, Disconnected
//-Connection
func connectToDevice () {
centralManager?.connect(blePeripheral!, options: nil)
}
func connectToAllDevices(){
var seconds = 0.0
for per in peripherals
{
DispatchQueue.main.asyncAfter(deadline: .now() + seconds) {
blePeripheral = per
print("Connecting naar " + (blePeripheral?.name!)!)
self.connectToDevice ()
}
seconds = seconds + 0.5;
}
}
/*
Invoked when a connection is successfully created with a peripheral.
This method is invoked when a call to connect(_:options:) is successful. You typically implement this method to set the peripheral’s delegate and to discover its services.
*/
//-Connected
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
print("*****************************")
print("Connection complete")
print("Peripheral info: \(String(describing: blePeripheral))")
//Erase data that we might have
data.length = 0
//Discovery callback
peripheral.delegate = self
//Only look for services that matches transmit uuid
peripheral.discoverServices([ParticlePeripheral.BLEService_UUID])
/*
//Once connected, move to new view controller to manager incoming and outgoing data
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let uartViewController = storyboard.instantiateViewController(withIdentifier: "UartModuleViewController") as! UartModuleViewController
uartViewController.peripheral = peripheral
navigationController?.pushViewController(uartViewController, animated: true)
*/
}
/*
Invoked when the central manager fails to create a connection with a peripheral.
*/
func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
if error != nil {
print("Failed to connect to peripheral")
return
}
}
func disconnectAllConnection() {
centralManager.cancelPeripheralConnection(blePeripheral!)
}
/*
Invoked when you discover the peripheral’s available services.
This method is invoked when your app calls the discoverServices(_:) method. If the services of the peripheral are successfully discovered, you can access them through the peripheral’s services property. If successful, the error parameter is nil. If unsuccessful, the error parameter returns the cause of the failure.
*/
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
print("*******************************************************")
if ((error) != nil) {
print("Error discovering services: \(error!.localizedDescription)")
return
}
guard let services = peripheral.services else {
return
}
//We need to discover the all characteristic
for service in services {
peripheral.discoverCharacteristics(nil, for: service)
// bleService = service
}
print("Discovered Services: \(services)")
}
/*
Invoked when you discover the characteristics of a specified service.
This method is invoked when your app calls the discoverCharacteristics(_:for:) method. If the characteristics of the specified service are successfully discovered, you can access them through the service's characteristics property. If successful, the error parameter is nil. If unsuccessful, the error parameter returns the cause of the failure.
*/
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
print("*******************************************************")
if ((error) != nil) {
print("Error discovering services: \(error!.localizedDescription)")
return
}
guard let characteristics = service.characteristics else {
return
}
print("Found \(characteristics.count) characteristics!")
for characteristic in characteristics {
//looks for the right characteristic
if characteristic.uuid.isEqual(ParticlePeripheral.BLE_Characteristic_uuid_Rx) {
rxCharacteristic = characteristic
//Once found, subscribe to the this particular characteristic...
peripheral.setNotifyValue(true, for: rxCharacteristic!)
// We can return after calling CBPeripheral.setNotifyValue because CBPeripheralDelegate's
// didUpdateNotificationStateForCharacteristic method will be called automatically
peripheral.readValue(for: characteristic)
print("Rx Characteristic: \(characteristic.uuid)")
}
if characteristic.uuid.isEqual(ParticlePeripheral.BLE_Characteristic_uuid_Tx){
txCharacteristic = characteristic
print("Tx Characteristic: \(characteristic.uuid)")
}
peripheral.discoverDescriptors(for: characteristic)
}
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverDescriptorsFor characteristic: CBCharacteristic, error: Error?) {
print("*******************************************************")
if error != nil {
print("\(error.debugDescription)")
return
}
guard let descriptors = characteristic.descriptors else { return }
descriptors.forEach { descript in
print("function name: DidDiscoverDescriptorForChar \(String(describing: descript.description))")
print("Rx Value \(String(describing: rxCharacteristic?.value))")
print("Tx Value \(String(describing: txCharacteristic?.value))")
}
}
func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {
print("*******************************************************")
if (error != nil) {
print("Error changing notification state:\(String(describing: error?.localizedDescription))")
} else {
print("Characteristic's value subscribed")
}
if (characteristic.isNotifying) {
print ("Subscribed. Notification has begun for: \(characteristic.uuid)")
}
}
func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
print("Disconnected")
}
func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
guard error == nil else {
print("Error discovering services: error")
return
}
print("Message sent")
}
func peripheral(_ peripheral: CBPeripheral, didWriteValueFor descriptor: CBDescriptor, error: Error?) {
guard error == nil else {
print("Error discovering services: error")
return
}
print("Succeeded!")
}
// MARK: - Getting Values From Characteristic
/** After you've found a characteristic of a service that you are interested in, you can read the characteristic's value by calling the peripheral "readValueForCharacteristic" method within the "didDiscoverCharacteristicsFor service" delegate.
*/
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
guard characteristic == rxCharacteristic,
let characteristicValue = characteristic.value,
let ASCIIstring = NSString(data: characteristicValue,
encoding: String.Encoding.utf8.rawValue)
else { return }
characteristicASCIIValue = ASCIIstring
let ontvangen = String(characteristicASCIIValue)
let waarde = haalwaarde(recieved: ontvangen)
print("Value Recieved: " + String(characteristicASCIIValue) )
NotificationCenter.default.post(name:NSNotification.Name(rawValue: "Notify"), object: self)
if(updateService){updateService=false; return}
if(!waarde.isNumber){print("waarde is no number");return}
if(Running ){Vervolg()}
}
func haalNode(recieved:String)->String{
//nodenr
if(recieved.count<10){return "fout";}
let temp = recieved
let lengte = recieved.count;
let start = temp.index(temp.startIndex, offsetBy: 7)
let end = temp.index(temp.endIndex, offsetBy: -(lengte-8))
let range = start..<end
let nodeNr = String(temp[range])
//print("nodeNr=", nodeNr)
return nodeNr
}
func haalwaarde(recieved:String)->String{
//Reactietijd
if(recieved.count<10){return "fout"};
let temp = recieved
let lengte = recieved.count;
let start = temp.index(temp.startIndex, offsetBy: 1)
let end = temp.index(temp.endIndex, offsetBy: -(lengte-7))
let range = start..<end
let Reactietijd = String(temp[range])
//print("\nreactietijd=", Reactietijd)
return Reactietijd
}
func startCyclus(){
currentNode = 0
if maxNodes == 0 {return}
Running = true
blePeripheral = peripherals[0]
updateService = true
blePeripheral?.discoverServices([ParticlePeripheral.BLEService_UUID])
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
self.writeValue(data: "N 5000G55")
currentNode += 1
}
func Vervolg(){
print("vervolg")
if currentNode == maxNodes {Running = false;return}
blePeripheral = peripherals[currentNode]
updateService = true
blePeripheral?.discoverServices([ParticlePeripheral.BLEService_UUID])
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10)) {
self.writeValue(data: "N 5000G55")
currentNode += 1
}
}
// Write functions
func writeValue(data: String){
print("schrijfdata " + String(currentNode))
let valueString = (data as NSString).data(using: String.Encoding.utf8.rawValue)
//change the "data" to valueString
if let blePer = blePeripheral{
if let txCharacteristic = txCharacteristic {
blePer.writeValue(valueString!, for: txCharacteristic, type: CBCharacteristicWriteType.withoutResponse)
}
}
}
/*
Invoked when the central manager’s state is updated.
This is where we kick off the scan if Bluetooth is turned on.
*/
func centralManagerDidUpdateState(_ central: CBCentralManager) {
if central.state == CBManagerState.poweredOn {
// We will just handle it the easy way here: if Bluetooth is on, proceed...start scan!
print("Bluetooth Enabled")
startScan()
} else {
//If Bluetooth is off, display a UI alert message saying "Bluetooth is not enable" and "Make sure that your bluetooth is turned on"
print("Bluetooth Disabled- Make sure your Bluetooth is turned on")
let alertVC = UIAlertController(title: "Bluetooth is not enabled", message: "Make sure that your bluetooth is turned on", preferredStyle: UIAlertControllerStyle.alert)
let action = UIAlertAction(title: "ok", style: UIAlertActionStyle.default, handler: { (action: UIAlertAction) -> Void in
self.dismiss(animated: true, completion: nil)
})
alertVC.addAction(action)
self.present(alertVC, animated: true, completion: nil)
}
}
}
extension String {
var isNumber: Bool {
let characters = CharacterSet.decimalDigits.inverted
return !self.isEmpty && rangeOfCharacter(from: characters) == nil
}
}
I think it's your logging is hiding what's really happening.
You reassign blePeripheral before each connection, but if any of them take longer than 0.5 seconds, by the time didConnect is called, the device that has connected won't be the one that's referred to by blePeripheral.
I would suggest removing blePeripheral entirely, and explicitly pass the CBPeripheral object into connectToDevice. Also, in didConnect, use the peripheral parameter that's passed in.

How to modify an existing BLECentral class into a singleton class?

Hi I'm trying to make the BLE Central class into a Singleton class?
I'm running into a few crashes while trying to implement it.
Here is my code:
//This is the BLE Central Class
import Foundation
import UIKit
import CoreBluetooth
var txCharacteristic : CBCharacteristic?
var rxCharacteristic : CBCharacteristic?
var blePeripheral : CBPeripheral?
var characteristicASCIIValue = NSString()
class BLECentralViewController : UIViewController, CBCentralManagerDelegate, CBPeripheralDelegate, UITableViewDelegate, UITableViewDataSource{
//Data
var centralManager : CBCentralManager!
var RSSIs = [NSNumber]()
var data = NSMutableData()
var writeData: String = ""
var peripherals: [CBPeripheral] = []
var characteristicValue = [CBUUID: NSData]()
var timer = Timer()
var characteristics = [String : CBCharacteristic]()
//UI
#IBOutlet weak var baseTableView: UITableView!
#IBOutlet weak var refreshButton: UIBarButtonItem!
#IBAction func refreshAction(_ sender: AnyObject) {
disconnectFromDevice()
self.peripherals = []
self.RSSIs = []
self.baseTableView.reloadData()
startScan()
}
override func viewDidLoad() {
super.viewDidLoad()
self.baseTableView.delegate = self
self.baseTableView.dataSource = self
self.baseTableView.reloadData()
centralManager = CBCentralManager(delegate: self, queue: nil)
let backButton = UIBarButtonItem(title: "Disconnect", style: .plain, target: nil, action: nil)
navigationItem.backBarButtonItem = backButton
}
override func viewDidAppear(_ animated: Bool) {
disconnectFromDevice()
super.viewDidAppear(animated)
refreshScanView()
print("View Cleared")
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
print("Stop Scanning")
centralManager?.stopScan()
}
/*Okay, now that we have our CBCentalManager up and running, it's time to start searching for devices. You can do this by calling the "scanForPeripherals" method.*/
func startScan() {
peripherals = []
print("Now Scanning...")
self.timer.invalidate()
centralManager?.scanForPeripherals(withServices: [BLEService_UUID] , options: [CBCentralManagerScanOptionAllowDuplicatesKey:false])
Timer.scheduledTimer(timeInterval: 17, target: self, selector: #selector(self.cancelScan), userInfo: nil, repeats: false)
}
/*We also need to stop scanning at some point so we'll also create a function that calls "stopScan"*/
func cancelScan() {
self.centralManager?.stopScan()
print("Scan Stopped")
print("Number of Peripherals Found: \(peripherals.count)")
}
func refreshScanView() {
baseTableView.reloadData()
}
//-Terminate all Peripheral Connection
/*
Call this when things either go wrong, or you're done with the connection.
This cancels any subscriptions if there are any, or straight disconnects if not.
(didUpdateNotificationStateForCharacteristic will cancel the connection if a subscription is involved)
*/
func disconnectFromDevice () {
if blePeripheral != nil {
// We have a connection to the device but we are not subscribed to the Transfer Characteristic for some reason.
// Therefore, we will just disconnect from the peripheral
centralManager?.cancelPeripheralConnection(blePeripheral!)
}
}
func restoreCentralManager() {
//Restores Central Manager delegate if something went wrong
centralManager?.delegate = self
}
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral,advertisementData: [String : Any], rssi RSSI: NSNumber) {
blePeripheral = peripheral
self.peripherals.append(peripheral)
self.RSSIs.append(RSSI)
peripheral.delegate = self
self.baseTableView.reloadData()
if blePeripheral == nil {
print("Found new pheripheral devices with services")
print("Peripheral name: \(String(describing: peripheral.name))")
print("**********************************")
print ("Advertisement Data : \(advertisementData)")
}
}
//Peripheral Connections: Connecting, Connected, Disconnected
//-Connection
func connectToDevice () {
centralManager?.connect(blePeripheral!, options: nil)
}
//-Connected
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
print("*****************************")
print("Connection complete")
print("Peripheral info: \(String(describing: blePeripheral))")
//Stop Scan- We don't need to scan once we've connected to a peripheral. We got what we came for.
centralManager?.stopScan()
print("Scan Stopped")
//Erase data that we might have
data.length = 0
//Discovery callback
peripheral.delegate = self
//Only look for services that matches transmit uuid
peripheral.discoverServices([BLEService_UUID])
//Once connected, move to new view controller to manager incoming and outgoing data
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let firstVC = storyboard.instantiateViewController(withIdentifier: "FirstViewController") as! FirstViewController
firstVC.peripheral = peripheral
navigationController?.pushViewController(firstVC, animated: true)
}
func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
if error != nil {
print("Failed to connect to peripheral")
return
}
}
func disconnectAllConnection() {
centralManager.cancelPeripheralConnection(blePeripheral!)
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
print("*******************************************************")
if ((error) != nil) {
print("Error discovering services: \(error!.localizedDescription)")
return
}
guard let services = peripheral.services else {
return
}
//We need to discover the all characteristic
for service in services {
peripheral.discoverCharacteristics(nil, for: service)
// bleService = service
}
print("Discovered Services: \(services)")
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
print("*******************************************************")
if ((error) != nil) {
print("Error discovering services: \(error!.localizedDescription)")
return
}
guard let characteristics = service.characteristics else {
return
}
print("Found \(characteristics.count) characteristics!")
for characteristic in characteristics {
//looks for the right characteristic
if characteristic.uuid.isEqual(BLE_Characteristic_uuid_Rx) {
rxCharacteristic = characteristic
//Once found, subscribe to the this particular characteristic...
peripheral.setNotifyValue(true, for: rxCharacteristic!)
// We can return after calling CBPeripheral.setNotifyValue because CBPeripheralDelegate's
// didUpdateNotificationStateForCharacteristic method will be called automatically
peripheral.readValue(for: characteristic)
print("Rx Characteristic: \(characteristic.uuid)")
}
if characteristic.uuid.isEqual(BLE_Characteristic_uuid_Tx){
txCharacteristic = characteristic
print("Tx Characteristic: \(characteristic.uuid)")
}
peripheral.discoverDescriptors(for: characteristic)
}
}
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
if characteristic == rxCharacteristic {
if let ASCIIstring = NSString(data: characteristic.value!, encoding: String.Encoding.utf8.rawValue) {
characteristicASCIIValue = ASCIIstring
print("Value Recieved: \((characteristicASCIIValue as String))")
NotificationCenter.default.post(name:NSNotification.Name(rawValue: "Notify"), object: nil)
}
}
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverDescriptorsFor characteristic: CBCharacteristic, error: Error?) {
print("*******************************************************")
if error != nil {
print("\(error.debugDescription)")
return
}
if ((characteristic.descriptors) != nil) {
for x in characteristic.descriptors!{
let descript = x as CBDescriptor!
print("function name: DidDiscoverDescriptorForChar \(String(describing: descript?.description))")
print("Rx Value \(String(describing: rxCharacteristic?.value))")
print("Tx Value \(String(describing: txCharacteristic?.value))")
}
}
}
func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {
print("*******************************************************")
if (error != nil) {
print("Error changing notification state:\(String(describing: error?.localizedDescription))")
} else {
print("Characteristic's value subscribed")
}
if (characteristic.isNotifying) {
print ("Subscribed. Notification has begun for: \(characteristic.uuid)")
}
}
func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
print("Disconnected")
}
func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
guard error == nil else {
print("Error discovering services: error")
return
}
print("Message sent")
}
func peripheral(_ peripheral: CBPeripheral, didWriteValueFor descriptor: CBDescriptor, error: Error?) {
guard error == nil else {
print("Error discovering services: error")
return
}
print("Succeeded!")
}
//Table View Functions
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.peripherals.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "BlueCell") as! PeripheralTableViewCell
let peripheral = self.peripherals[indexPath.row]
let RSSI = self.RSSIs[indexPath.row]
if peripheral.name == nil {
cell.peripheralLabel.text = "nil"
} else {
cell.peripheralLabel.text = peripheral.name
}
cell.rssiLabel.text = "RSSI: \(RSSI)"
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
blePeripheral = peripherals[indexPath.row]
connectToDevice()
}
func centralManagerDidUpdateState(_ central: CBCentralManager) {
if central.state == CBManagerState.poweredOn {
// We will just handle it the easy way here: if Bluetooth is on, proceed...start scan!
print("Bluetooth Enabled")
startScan()
} else {
//If Bluetooth is off, display a UI alert message saying "Bluetooth is not enable" and "Make sure that your bluetooth is turned on"
print("Bluetooth Disabled- Make sure your Bluetooth is turned on")
let alertVC = UIAlertController(title: "Bluetooth is not enabled", message: "Make sure that your bluetooth is turned on", preferredStyle: UIAlertControllerStyle.alert)
let action = UIAlertAction(title: "ok", style: UIAlertActionStyle.default, handler: { (action: UIAlertAction) -> Void in
self.dismiss(animated: true, completion: nil)
})
alertVC.addAction(action)
self.present(alertVC, animated: true, completion: nil)
}
}
}
My questions are:
How can I modify the BLECentral class to use as a singleton so I
can call from any view controller class to read and write data?
Can I simply make the first view controller as a singleton instead of the BLE central and read/write by calling this from other view controller class?
Or can I extend the first view controller class scope by using
extension?
I'm currently able to read/write data but peripheral doesn't seem to
be called properly sometimes, therefore gets disconnected? Any
suggestions/fixes?
Here is my FirstViewController class:
class FirstViewController: UIViewController, UIPeripheralManagerDelegate {
var peripheralManager: CBPeripheralManager?
var peripheral: CBPeripheral!
viewDidLoad(){
//I'm calling the blePeripheral from BLE class to the peripheral in the current class
peripheral = blePeripheral
}
//I have a button here to send some data and only when I receive the data I want to go to the next view controller
#IBAction func login(_sender: AnyObject) {
//This is my write code
let bytes : [UInt8] = [ 0x1A, 0x2B, 0x3C, 0x4D ]
let Transmitdata = NSData(bytes: bytes, length: bytes.count)
peripheral.writeValue(Transmitdata as Data, for: txCharacteristic!, type: CBCharacteristicWriteType.withoutResponse)
print("Data Sent",Transmitdata)
//Give time for data to be received fromdevice
sleep(1)
//let ReceiveData = rxCharacteristic?.value
if let ReceiveData = ReceiveData {
let ReceivedNoOfBytes = ReceiveData.count
var ReceivedByteArray = [UInt8](repeating: 0, count: ReceivedNoOfBytes)
(ReceiveData as NSData).getBytes(&ReceivedByteArray, length: ReceivedNoOfBytes)
print("Data Received ",ReceivedByteArray)
//checking if we received the right data?
if(ReceivedByteArray[0] == 10 && ReceivedByteArray[1] == 20 && ReceivedByteArray[2] == 30 && ReceivedByteArray[3] == 40){
performSegue(withIdentifier: "Second_View", sender: self)
}
}
}
And the SecondViewController class:
class SecondViewController: UIViewController{
var firstview: FirstViewController?
var peripheralManager: CBPeripheralManager?
var peripheral: CBPeripheral!
override func viewWillAppear(_animated: Bool){
let peripheral = firstview?.peripheral
let peripheralManager = firstview?.peripheralManager
}
//I have another button here to direct me to third view controller class
#IBAction func mainmenu(_sender: AnyObject){
//send some bytes
//receiver some bytes
//similar to the first view controller
If correct data is received
{
performSegue(withIdentifier: "Main_M", sender: self)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?){
if segue.destination is Main_M
{
let gotoM = segue.destination as? Main_M
gotoM?.peripheral = firstview?.peripheral
}
}

Updating code to Swift 3

I am a beginner to programming with swift and programming in general. I am currently working on an app which allows one phone to send a message (peripheral) to another which will receive the message (central). I have taken most of the code from an app built using swift 2 and have tweaked it slightly to remove any errors. As a result, my code is a jumble of swift 2/3 (or so I have been told). I am not sure how to update this code fully to swift 3 which I need someones help to do. I believe it is the IBActions and delegates that are outdated but I am completely clueless on how to amend it.
I have tried running the app and it runs successfully but when I press any of the buttons nothing happens as far as I can tell. I have a basic understanding of what my code does and what each function is there for but I find myself stuck on what to do for it to work. If anyone has experience working with Bluetooth via swift and can see what I am doing wrong or perhaps if I haven't included something important. I am led to believe the issue is that all the code has not been updated to swift 3 but I can't be sure. I have read the Apple documentation for Core bluetooth.
PS: I know this question is very vague as I am unsure on what part of my code I need to fix so it is very difficult to make it specific to a single issue. Sorry!
import UIKit
import CoreBluetooth
class ViewController: UIViewController, CBPeripheralManagerDelegate, CBCentralManagerDelegate, CBPeripheralDelegate {
let messageUUID = CBUUID(string: "053D6600-821E-46A7-AC25-43A81D948E8B")
let inputUUID = CBUUID(string: "49A79D26-5323-4374-81EA-29B099AF85C8")
let otherUUID = CBUUID(string: "053D6600-821E-46A7-AC25-43A81D948E87")
var peripheralManager: CBPeripheralManager!
var characteritic: CBMutableCharacteristic!
var getDataPeripheralCharacteristic: CBMutableCharacteristic!
var service: CBMutableService!
var outputData:String = ""
var centralManager: CBCentralManager!
var connectingPeripheral: CBPeripheral?
var centralWriteCharacteristic: CBCharacteristic!
#IBOutlet var inputLabel: UITextField!
#IBOutlet weak var outputLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func centralMode(_ sender: UIButton) {
centralManager = CBCentralManager(delegate: self, queue: nil)
peripheralManager = nil
}
#IBAction func peripheralMode(_ sender: UIButton) {
peripheralManager = CBPeripheralManager(delegate: self, queue: nil)
centralManager = nil
}
#IBAction func sendData(_ sender: UIButton) {
if (peripheralManager != nil) {
let passed = peripheralManager.updateValue(inputLabel.text!.data(using: String.Encoding.utf8)!, for: characteritic!, onSubscribedCentrals: nil)
if passed == false {
print("error couldn't send data")
}
}
if (centralManager != nil) {
if (connectingPeripheral != nil) {
connectingPeripheral?.writeValue(inputLabel.text!.data(using: String.Encoding.utf8)!, for: centralWriteCharacteristic, type: CBCharacteristicWriteType.withResponse)
}
}
}
func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
if (peripheral.state == .poweredOn) {
characteritic = CBMutableCharacteristic(type: messageUUID, properties: CBCharacteristicProperties.notify, value: nil, permissions: CBAttributePermissions.readable)
getDataPeripheralCharacteristic = CBMutableCharacteristic(type: inputUUID, properties:
CBCharacteristicProperties.write, value: nil, permissions: CBAttributePermissions.writeable)
service = CBMutableService(type: otherUUID, primary: true)
service.characteristics = [characteritic!, getDataPeripheralCharacteristic!]
peripheralManager!.add(service)
}
}
func peripheralManager(peripheral: CBPeripheralManager, didAddService service: CBService, error: NSError?) {
peripheral.stopAdvertising()
let identifier = Bundle.main.bundleIdentifier!
let manufacturerData = identifier.data(using: String.Encoding.utf8, allowLossyConversion: false)
let dataToBeAdvertised:[String: Any] = [
CBAdvertisementDataLocalNameKey : "Sample peripheral",
CBAdvertisementDataManufacturerDataKey : manufacturerData as Any,
CBAdvertisementDataServiceUUIDsKey : [messageUUID, inputUUID],
]
peripheralManager.startAdvertising(dataToBeAdvertised)
}
func peripheralManager(peripheral: CBPeripheralManager, didReceiveWriteRequests requests: [CBATTRequest]) {
for request in requests {
if (request.characteristic.uuid.uuidString == inputUUID.uuidString) {
outputData = String(data: request.value!, encoding: String.Encoding.utf8)!
outputLabel.text = outputData
}
}
}
func peripheralManager(peripheral: CBPeripheralManager, didReceiveReadRequest request: CBATTRequest) {
}
func peripheralManager(peripheral: CBPeripheralManager, central: CBCentral, didSubscribeToCharacteristic characteristic: CBCharacteristic) {
outputLabel.text = "Press send message"
print("Now connected")
}
func centralManagerDidUpdateState(_ central: CBCentralManager) {
if central.state == .poweredOn {
centralManager.scanForPeripherals(withServices: nil, options: nil)
//search for peripheral device
}
}
//when peripheral is discovered, this method is called
private func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) {
self.centralManager.stopScan();
self.connectingPeripheral = peripheral;
peripheral.delegate = self;
centralManager.connect(peripheral, options: nil)
}
//if connection request from central is succesfull, this method is called
func centralManager(central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) {
peripheral.delegate = self;
peripheral.discoverServices(nil)
}
//if central discovers services, this method is called
private func peripheral(peripheral: CBPeripheral, didDiscoverServices error: NSError?) {
for service: CBService in peripheral.services! {
peripheral.discoverCharacteristics(nil, for: service)
}
}
private func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError?) {
if (service.uuid.uuidString == otherUUID.uuidString) {
guard let characteristics = service.characteristics else {
return
}
for characteristic in characteristics {
if characteristic.uuid.uuidString == messageUUID.uuidString {
peripheral.setNotifyValue(true, for: characteristic)
} else if characteristic.uuid.uuidString == inputUUID.uuidString {
centralWriteCharacteristic = characteristic
}
}
}
}
private func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) {
if error != nil {
print("Error reading characteristics");
}
if (characteristic.uuid == messageUUID) {
outputData = String(data: characteristic.value!, encoding: String.Encoding.utf8)!
print(outputData)
outputLabel.text = outputData
}
}
}
If the issue is because of swift 2/3 mismatch. Try upgrading your code to swift3.
Go to Xcode-edit-convert- to current swift syntax.
This will lead to few build errors, identify them and fix them.
Make your sure if you have any pod or cart file , do not forget to upgrade them as well.
Hopefully this should resolve your issue.

iOS BLE app - I can get notifications from a characteristic, but can't read it

I've been working on an iOS app that interfaces with a BLE device. The device has 1 service with 5 characteristics. Three of them are read/notify, while the other two are read/write/notify.
When I first launch the app, I need to read the 5 characteristics, then listen for future notifications. For some reason, the read is not working (no response to readValueForCharacteristic), but the notifications do work (changes on the device show up in the app).
Also unusual - I never receive calls to didUpdateNotificationStateForCharacteristic, despite the fact that the notifications do indeed work.
I also am unable to write to the 2 writable characteristics, though that isn't my primary concern right now. I've verified none of these problems are on the device end, because I can perform them using the LightBlue.app
Here's my code:
import UIKit
import CoreBluetooth
class ViewController: UIViewController, CBCentralManagerDelegate, CBPeripheralDelegate {
// GUI elements
#IBOutlet var statusLabel: UILabel!
#IBOutlet var char1Field: UITextField!
#IBOutlet var char2Field: UITextField!
#IBOutlet var char3Field: UITextField!
#IBOutlet var char4Selector: UISegmentedControl!
#IBOutlet var char5Field: UITextField!
// BLE
var centralManager : CBCentralManager!
var myPeriph : CBPeripheral!
var char3 : CBCharacteristic!
var char4 : CBCharacteristic!
var value1 : UInt32 = 0
var value2 : UInt32 = 0
var value3 : Float32 = 0
var value4 : UInt8 = 0
var value5 : UInt8 = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// Initialize central manager on load
centralManager = CBCentralManager(delegate: self, queue: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func char3FieldChanged(sender: AnyObject) {
if char3Field.text == "" {
value3 = 0
} else {
value3 = Float32(char3Field.text!)!
}
let wtBytes = NSData(bytes: &value3, length: sizeof(UInt8))
char3Field.text = String(format: "%0.1f", arguments: [value3])
if char3 != nil {
self.myPeriph.writeValue(wtBytes, forCharacteristic: char3, type: CBCharacteristicWriteType.WithoutResponse)
}
}
#IBAction func char4SelectorChanged(sender: AnyObject) {
value4 = UInt8(char4Selector.selectedSegmentIndex)
let char4Bytes = NSData(bytes: &value4, length: sizeof(UInt8))
if char4 != nil {
self.myPeriph.writeValue(char4Bytes, forCharacteristic: char4, type: CBCharacteristicWriteType.WithoutResponse)
}
}
/******* CBCentralManagerDelegate *******/
// Check status of BLE hardware
func centralManagerDidUpdateState(central: CBCentralManager) {
if central.state == CBCentralManagerState.PoweredOn {
// Scan for peripherals if BLE is turned on
central.scanForPeripheralsWithServices(nil, options: nil)
self.statusLabel.text = "Searching for BLE Devices"
}
else {
// Can have different conditions for all states if needed - show generic alert for now
showAlertWithText("Error", message: "Bluetooth switched off or not initialized")
}
}
// Check out the discovered peripherals to find Sensor Tag
func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) {
if MyPeriph.NameFound(advertisementData) == true {
// Update Status Label
self.statusLabel.text = "Device Found"
// Stop scanning, set as the peripheral to use and establish connection
self.centralManager.stopScan()
self.myPeriph = peripheral
self.myPeriph.delegate = self
self.centralManager.connectPeripheral(peripheral, options: nil)
}
else {
self.statusLabel.text = "Device NOT Found"
}
}
// Discover services of the peripheral
func centralManager(central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) {
self.statusLabel.text = "Discovering peripheral services"
peripheral.discoverServices(nil)
print("Searching for peripheral")
}
// If disconnected, start searching again
func centralManager(central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: NSError?) {
self.statusLabel.text = "Disconnected"
central.scanForPeripheralsWithServices(nil, options: nil)
print("Disconnected")
}
/******* CBCentralPeripheralDelegate *******/
// Check if the service discovered is valid
func peripheral(peripheral: CBPeripheral, didDiscoverServices error: NSError?) {
self.statusLabel.text = "Looking at peripheral services"
for service in peripheral.services! {
let thisService = service as CBService
if MyPeriph.validService(thisService) {
// Discover characteristics of all valid services
peripheral.discoverCharacteristics(nil, forService: thisService)
print("Peripheral service found, searching for characteristics")
}
}
}
func peripheral(peripheral: CBPeripheral, didUpdateNotificationStateForCharacteristic characteristic: CBCharacteristic, error: NSError?) {
print("Did update notify status for \(characteristic.description)")
}
func peripheral(peripheral: CBPeripheral, didUpdateValueForDescriptor descriptor: CBDescriptor, error: NSError?) {
print("Did update value for descriptor")
}
// Enable notification and sensor for each characteristic of valid service
func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError?) {
self.statusLabel.text = "Configuring..."
print("Found \(service.characteristics?.count) characteristics")
for characteristic in service.characteristics! {
let thisCharacteristic = characteristic as CBCharacteristic
self.myPeriph.readValueForCharacteristic(thisCharacteristic)
self.myPeriph.discoverDescriptorsForCharacteristic(thisCharacteristic)
switch characteristic.UUID {
case Char1Uuid:
self.myPeriph.setNotifyValue(true, forCharacteristic: thisCharacteristic)
case Char2Uuid:
self.myPeriph.setNotifyValue(true, forCharacteristic: thisCharacteristic)
case Char3Uuid:
self.myPeriph.setNotifyValue(true, forCharacteristic: thisCharacteristic)
char3 = characteristic
case Char4Uuid:
self.myPeriph.setNotifyValue(true, forCharacteristic: thisCharacteristic)
char4 = characteristic
case Char5Uuid:
self.myPeriph.setNotifyValue(true, forCharacteristic: thisCharacteristic)
default: break
}
}
}
// Get data values when they are updated
func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) {
self.statusLabel.text = "Connected"
switch characteristic.UUID {
case Char1Uuid:
value1 = MyPeriph.getvalue1(characteristic.value!)
char1Field.text = String(value1)
case Char2Uuid:
value2 = MyPeriph.getvalue2(characteristic.value!)
char2Field.text = String(value2)
case Char3Uuid:
value3 = MyPeriph.getvalue3(characteristic.value!)
char3Field.text = String(value3)
char3 = characteristic
case Char4Uuid:
value4 = MyPeriph.getvalue4(characteristic.value!)
if value4 == 0 {
char4Selector.selectedSegmentIndex = 0
} else {
char4Selector.selectedSegmentIndex = 1
}
char4 = characteristic
case Char5Uuid:
value5 = MyPeriph.getvalue5(characteristic.value!)
char5Field.text = String(value5)
default: break
}
}
/******* Helper *******/
// Show alert
func showAlertWithText (header : String = "Warning", message : String) {
let alert = UIAlertController(title: header, message: message, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
alert.view.tintColor = UIColor.redColor()
self.presentViewController(alert, animated: true, completion: nil)
}
}

Resources