DanB DanB - 3 months ago 61
iOS Question

Write Data to Characteristic on Button Click - Swift

I've managed to connect an ios app to my BLE hm-10 device and send it's characteristic a string. However I can't figure out how to send the string once a button is pressed using the @IBAction function.

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)

}


When I put this code into the @IBAction function shown at the bottom it does not work as "characteristic" is an unresolved identifier. Is there a way to link this to the peripheral function? I'm relatively new to coding in Swift so any help would be really appreciated. Thanks.

Answer
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)

    }
}
Comments