我正试图通过蓝牙点击按钮发送数据。我可以在打开应用程序时使用以下代码发送数据:
var manager: CBCentralManager!
var device: CBPeripheral?
var characteristics: [CBCharacteristic]?
var serviceUUID = "1234"
var char1 = "FFE1"
let deviceName = "HMSoft"
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
DidDiscoverChar.text = "Characteristic found!"
device = peripheral
characteristics = service.characteristics
var value: UInt8 = 1
let data = NSData(bytes: &value, length: MemoryLayout<UInt8>.size)
for characteristic in service.characteristics as [CBCharacteristic]!
{
if(characteristic.uuid.uuidString == "FFE1")
{
device?.writeValue(data as Data, for: characteristic,type: CBCharacteristicWriteType.withoutResponse)
}
}
}
但是当我尝试用按钮发送它时:
@IBAction func ledOn(_ sender: AnyObject) {
var value: UInt8 = 1
let data = NSData(bytes: &value, length: MemoryLayout<UInt8>.size)
device?.writeValue(data as Data, for: characteristics,type: CBCharacteristicWriteType.withoutResponse)
}
我收到错误:
无法转换'[CBCharacteristic]类型的值?'预期参数类型'CBCharacteristic'
这似乎是一件容易的事,但作为一个新手,我被卡住了。
编辑:(回应rmaddy的回答)
正如你所建议的,它确实在迭代数组中工作,如下所示。
@IBAction func ledOn(_ sender: AnyObject) {
var value: UInt8 = 1
let data = NSData(bytes: &value, length: MemoryLayout<UInt8>.size)
for characteristic in characteristics as [CBCharacteristic]!
{
if(characteristic.uuid.uuidString == "FFE1")
{
device?.writeValue(data as Data, for: characteristic,type: CBCharacteristicWriteType.withoutResponse)
}
}
}
由于我想作为程序员进行改进,我希望代码更高效。所以我想我可以在按钮功能之外进行迭代,以避免每次按下按钮时的迭代。为了说明我在操场上做了一个简单的例子:
var characteristicFFE1: String = ""
var array = ["r1", "r2", "r3", "FFE1", "r4"]
for uuidString in array {
if uuidString == "FFE1" {
characteristicFFE1 = uuidString
}
}
然后在IBAction中的writeValue中直接使用characteristicFFE1,如下所示:
@IBAction func ledOn(_ sender: AnyObject) {
var value: UInt8 = 1
let data = NSData(bytes: &value, length: MemoryLayout<UInt8>.size)
device?.writeValue(data as Data, for: characteristicsFFE1,type: CBCharacteristicWriteType.withoutResponse)
}
我试图完成上述操作,如下所示:
var characteristicFFE1: CBCharacteristic?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
for characteristic in characteristics as [CBCharacteristic]! //ERROR HERE
{
if(characteristic.uuid.uuidString == "FFE1")
{
characteristicFFE1 = characteristic
}
}
但我得到错误:线程1:致命错误:在展开Optional值时意外发现nil。
任何人都知道如何解决这个问题?我读过关于选项和解包的内容,但在这里仍然感到困惑。
答案 0 :(得分:2)
你的问题在这里
device?.writeValue(data as Data, for: characteristics,type: CBCharacteristicWriteType.withoutResponse)
您想发送一个您在此处声明的CBCharacteristic
类型的可选数组
var characteristics: [CBCharacteristic]?
虽然参数应该是CBCharacteristic
类型的值,您应该在使用之前进行初始化
var characteristics: CBCharacteristic?
以下是来自Docs
的方法签名func writeValue(_ data:Data, for characteristic:CBCharacteristic,type:CBCharacteristicWriteType)