·Language: Swift
·Bluetooth device used: Texas Instruments CC2541 SensorTag
Sorry for the beginner's question.
This is my first time to ask you a question, so I would appreciate it if you could let me know if it is easier to answer if you write it like this.
Currently, we are trying to create something that reflects data updates on the View when the Bluetooth button is pressed.
I was referring to a book called iOS×BLE Core Bluetooth Programming, and I was able to view updated data such as "left" and "right" in real time whenever the sensorTag button was pressed in the Central Manager and Peripheral Class (ViewController).
However, trying to view this data in a different class of ViewController does not work because it is not reflected in real time.I tried using segue to pass the data, but it was not updated in real time, but it was displayed as it was when I gave it to you.
I couldn't consider how to solve the problem, so I asked you a question.
It may be simple, but please forgive me as I am a beginner in programming.
Below is the code.
ViewController.swift
import UIKit
import CoreBluetooth
classViewController:UIViewController, CBC CentralManagerDelegate, CBPeripheralDelegate{
varisScanning=false
var centralManager —CBC CentralManager!
var peripheral —CBPeripheral!
@IBOutlet weak var label: UILabel!
varchara=NSData()
override func viewDidLoad(){
super.viewDidLoad()
// Central Manager Initialization
self.centralManager = CBC CentralManager (delegate:self, queue:nil)
}
override funcdidReceiveMemoryWarning(){
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// =========================================================================
// MARK:CBC CentralManagerDelegate
// be referred to as changing the state of the central manager
US>func centralManagerDidUpdateState(central:CBC CentralManager!){
println("state:\(central.state)")
}
// be called discovering devices around
centralManager (central:CBC CentralManager!,
DidDiscoverPeripheralPeripheral!,
advertisementData: NSObject: AnyObject!,
RSSI: NSNumber!)
{
println("Discovered BLE Device:\(peripheral)")
if(peripheral.name?.hasPrefix("konashi")!=nil){
self.peripheral=peripheral
self.centralManager.connectPeripheral(self.peripheral, options:nil)
}
}
// be referred to as a successful connection to the peripheral
centralManager (central:CBC CentralManager!,
DidConnectPeripheral peripheral: CBPeripheral!)
{
println("Connection successful!")
// Set delivery to receive service discovery results
peripheral.delegate=self
// Start Service Discovery
peripheral.discoverServices(nil)
}
// referred to as failure of connection to peripheral
centralManager (central:CBC CentralManager!,
DidFailToConnectPeripheral peripheral: CBPeripheral!,
error —NSError!)
{
println("Connection failed...")
}
// =========================================================================
// MARK:CBPeripheralDelegate
// be called upon service discovery
funcperipheral(peripheral:CBPeripheral!, didDiscoverServices error:NSError!){
if(error!=nil){
println("Error:\(error)")
return
}
let services —NSArray=peripheral.services
println("\(services.count) Found services!\(services)")
for obj in services {
iflet service=obj as?CBService{
// Start characteristic search
peripheral.discoverCharacteristics(nil, forService:service)
}
}
}
// be called upon the discovery of a characteristic
func peripheral (peripheral:CBPeripheral!,
didDiscoverCharacteristicsForService service:CBService!,
error —NSError!)
{
if(error!=nil){
println("Error:\(error)")
return
}
let characteristics —NSArray=service.characteristics
for obj in characteristics {
if let characteristic = obj as ? CBCharacteristic {
// start receiving update notifications
peripheral.setNotifyValue(
true,
forCharacteristic:characteristic)
}
}
}
// Called at Notify start/stop
func peripheral (peripheral:CBPeripheral!,
DidUpdateNotificationStateForCharacteristiccharacteristic:CBCCharacteristic!,
error —NSError!)
{
if error!=nil{
println("Notify state update failed... error:\(error)")
}
else{
println("Notify state update succeeded! characteristic UUID:\(characteristic.UUID), isNotifying:\(characteristic.isNotifying)")
}
}
// be called during data update
func peripheral (peripheral:CBPeripheral!,
DidUpdateValueForCharacteristiccharacteristic!,
error —NSError!)
{
if error!=nil{
println("Data update notification error:\(error)")
return
}
println("Data update! characteristic UUID:\(characteristic.UUID), value:\(characteristic.value)")
/**
From the Sensor Tag button
* <00>
* button-released
* <01>
* The right button was pressed.
* <02>
* The left button was pressed.
get one of the NSData returns
*/
varkeyPress —UInt8 = 0
characteristic.value.getBytes(&keyPress, length:1)
chara=characteristic.value
println("The contents of the character are \(chara)")
if(keyPress==0){
println("Button not pressed")
label?.text="Not pressed"
} else if(keyPress==1){
label ?.text="right"
println("Right button pressed")
} else if(keyPress==2){
label?.text="left"
println ("left button pressed")
} else if(keyPress==3){
}
}
// =========================================================================
// MARK:Actions
@ IBAction func scanBtnTapped (sender: UIButton) {
if!isScanning{
isScanning = true
self.centralManager.scanForPeripheralsWithServices(nil, options:nil)
sender.setTitle("STOP SCAN", forState:UIControlState.Normal)
}
else{
self.centralManager.stopScan()
sender.setTitle("START SCAN", forState:UIControlState.Normal)
isScanning=false
}
}
}
NextViewController.swift
import UIKit
classNextViewController:UIViewController {
@IBOutlet weak var label 2: UILabel!
override func viewDidLoad(){
super.viewDidLoad()
varchara2 = ViewController().chara
println(chara2)
varkeyPress2—UInt8=0
chara2.getBytes(&keyPress2,length:1)
println(keyPress2)
if(keyPress2==0){
println("Button not pressed 2")
} else if(keyPress2==1){
println("Right Button Pressed 2")
} else if(keyPress2==2){
println("left button pressed 2")
} else if(keyPress2==3){
println("Both buttons are pressed 2")
}
}
override funcdidReceiveMemoryWarning(){
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Each time you press the SensorTag button, the UILabel displays characters like "right" or "left".This cannot be viewed in another class (another UIViewController?).
ios swift bluetooth uikit
What is nextViewController.swift line 10 var chara2=ViewController().chara
trying to do?I'm trying to get the value of the property chara
right after generating the ViewController
, so it should be data of nil
or byte length 0, so what's the point of getting that?That's my honest impression.
When creating a new iOS application, the template you can use if you select master-Detail Application is used as a reference for "how to pass data in segue".
By carefully analyzing the code one line at a time, you will get something useful.
Since both centralManager delete and peripheral delete are self(=ViewController), the state change of centralManager and peripheral can only be seen by viewController.
If you want to know the state of centralManager or peripheral in multiple Views or ViewControllers, we recommend that you create a BLE-only class that inherits NSObject and have centralManager or peripheral in its properties.
CentralManager and peripheral state changes are received by self (=BLE-only class), and if you want to know about BLE-related state changes,
Notification or delete (protocol) or KVO.
I think the design is good.
I think this is a general concept of application design that can be used not only in Swift but also in Objective-C and other languages.
It may be difficult because of the suddenness, but I would appreciate it if you could help me even a little.
891 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
568 rails db:create error: Could not find mysql2-0.5.4 in any of the sources
600 GDB gets version error when attempting to debug with the Presense SDK (IDE)
© 2024 OneMinuteCode. All rights reserved.