gpt4 book ai didi

ios - 单击按钮时将数据写入特征 - Swift

转载 作者:可可西里 更新时间:2023-11-01 01:32:16 24 4
gpt4 key购买 nike

我已经成功地将一个 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 进行编码比较陌生,因此非常感谢任何帮助。谢谢。

最佳答案

class viewController: UIViewController {

var _peripheral: CBPeripheral?
var _characteristics: [CBCharacteristic]?

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)

let characteristic = //get right on out of _characteristics! array
_peripheral!.writeValue(data!, forCharacteristic: characteristic, type: CBCharacteristicWriteType.WithoutResponse)

}
}

关于ios - 单击按钮时将数据写入特征 - Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39119113/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com