我已經成功的iOS應用程序連接到我的BLE HM-10設備和發送它的特性的字符串。然而,我不知道如何使用@IBAction函數按下按鈕後發送字符串。將數據寫入特性的按鈕點擊 - 斯威夫特
func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error:NSError?)
{
print("Found \(service.characteristics!.count) characteristics!: \(service.characteristics)")
_peripheral = peripheral
_characteristics = service.characteristics
let string = "off"
let data = string.dataUsingEncoding(NSUTF8StringEncoding)
for characteristic in service.characteristics as [CBCharacteristic]!
{
if(characteristic.UUID.UUIDString == "FFE1")
{
print("sending data")
peripheral.writeValue(data!, forCharacteristic: characteristic,type: CBCharacteristicWriteType.WithoutResponse)
}
}
}
@IBAction func onButtonTouch(sender: UIButton)
{
let string = "on"
let data = string.dataUsingEncoding(NSUTF8StringEncoding)
_peripheral.writeValue(data!, forCharacteristic: _characteristics, type: CBCharacteristicWriteType.WithoutResponse)
}
當我把這個代碼成它不作爲工作底部顯示的@IBAction功能「特徵」是一個未解決的識別符。有沒有辦法將它鏈接到外設功能?我在Swift編碼方面比較新,所以任何幫助都會非常感謝。謝謝。
您需要保存的特點。在'onButtonTouch(sender:)'它沒有聲明! – Larme
爲什麼不能將'peripheral'和'characteristic'設置爲全局變量? – D4ttatraya
@Larme感謝您快速回答。真的很抱歉聽起來像這樣的新手,但你能向我解釋如何做到這一點?謝謝! – DanB