Swift 蓝牙单例 Class 处理程序
Swift Bluetooth singleton Class handler
嗨,我有一个蓝牙单例 class,我想在更新值时将我的蓝牙连接状态传递给我的 viewcontroller。我认为需要一些听众。
我的蓝牙class在这里
class Bluetooth:NSObject, CBCentralManagerDelegate, CBPeripheralDelegate {
static var instance = Bluetooth()
func initBluetoothSingleton(){}
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
if characteristic.uuid == BLE_WIFI_EVENT_CHARACTERISTIC_CBUUID {
let wifiEvent = ReadWiFiEvent(using: characteristic)
if(wifiEvent == "connect"){
// i want to pass data to my viewcontroller to show alert
}
}
}
func handlerBleStatus(completion: (status:String) -> ()) {
completion(status: "connect")
}
而我的 viewcontroller 在 viewdidload 或某处是这样的
Bluetooth.instance.handlerBleStatus { (status) in
print(status) //how to set a listener here
}
我想在我的 ble updatevalue 时设置一个侦听器然后显示警报让用户知道状态
这种情况需要用户协议吗?
谢谢
您可以通过多种方式发送值。使用协议、闭包或通知中心。
我相信使用闭包对你的情况很有效。
在Bluetooth
class
中定义一个变量
static var instance = Bluetooth()
var handleBleStatus: ((String) -> Void)?
在您的视图中设置闭包 controller/model。
Bluetooth.instance.handleBleStatus = { value in
print(value)
// TODO: Display alert
}
然后您可以使用闭包从 Bluetooth
class 发送值。您设置闭包变量的视图将获得更新。
if(wifiEvent == "connect"){
// i want to pass data to my viewcontroller to show alert
handleBleStatus?("Status: Connected")
}
嗨,我有一个蓝牙单例 class,我想在更新值时将我的蓝牙连接状态传递给我的 viewcontroller。我认为需要一些听众。
我的蓝牙class在这里
class Bluetooth:NSObject, CBCentralManagerDelegate, CBPeripheralDelegate {
static var instance = Bluetooth()
func initBluetoothSingleton(){}
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
if characteristic.uuid == BLE_WIFI_EVENT_CHARACTERISTIC_CBUUID {
let wifiEvent = ReadWiFiEvent(using: characteristic)
if(wifiEvent == "connect"){
// i want to pass data to my viewcontroller to show alert
}
}
}
func handlerBleStatus(completion: (status:String) -> ()) {
completion(status: "connect")
}
而我的 viewcontroller 在 viewdidload 或某处是这样的
Bluetooth.instance.handlerBleStatus { (status) in
print(status) //how to set a listener here
}
我想在我的 ble updatevalue 时设置一个侦听器然后显示警报让用户知道状态 这种情况需要用户协议吗?
谢谢
您可以通过多种方式发送值。使用协议、闭包或通知中心。
我相信使用闭包对你的情况很有效。
在Bluetooth
class
static var instance = Bluetooth()
var handleBleStatus: ((String) -> Void)?
在您的视图中设置闭包 controller/model。
Bluetooth.instance.handleBleStatus = { value in
print(value)
// TODO: Display alert
}
然后您可以使用闭包从 Bluetooth
class 发送值。您设置闭包变量的视图将获得更新。
if(wifiEvent == "connect"){
// i want to pass data to my viewcontroller to show alert
handleBleStatus?("Status: Connected")
}