[英]Core Bluetooth Function
因此過去幾天一直在網上搜索,但似乎仍然找不到有效的解決方案。 我正在運行Core Bluetooth,正在嘗試從Arduino獲取數據。 這是代碼:
//Reading Bluetooth Data
func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) {
let data = characteristic.value
if let str:String = String(data: data!, encoding: NSUTF8StringEncoding) {
self.delegate?.serialDidReceiveString(str)
print(str)
}
}
我可以毫無問題地使用print(str)
看到傳入的數據,但是我將如何將接收到的數據傳輸到另一個swift文件中,並最終將其顯示在UILabel上? 每當我嘗試在函數外使用str
,Xcode都會不斷告訴“期望的聲明”。 我對代表的嘗試如下:
protocol BluetoothSerialDelegate {
func serialDidReceiveString(message: String)
}
extension BluetoothSerialDelegate {
func serialDidReceiveString(message: String) {}
}
在函數所在的類中定義此變量var delegate: BluetoothSerialDelegate!
雖然沒有錯誤,但我打電話時
func serialDidReceiveString(message: String) {
Label.text! = message
print(message)
}
在ViewController內部,我無法像從初始函數中調用數據那樣看到數據。 可能是什么問題? 提前致謝!
在h文件中聲明該字符串,以便您具有全局變量。 或者,您可以僅將其保存為用戶默認值,這將使從其他文件訪問變得很容易。
您有一名代表...為什么不使用它? 在您想要顯示數據的類中,遵循您的委托,並實現委托方法serialDidReceiveString:
然后,當接收到數據時,將在另一個視圖中調用委托方法,然后可以更新標簽。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.