iosiphoneswiftbluetooth-lowenergyswift4

How to send data to bluetooth LE in iOS


I am newbie to bluetooth communication. My task is to write data to bluetooth with commonand. The commonand is 0x61 and I need to pass 01-02-03-04 4 byte value to it. I have recognized charcteristics.

I want answer in swift 4.

  let string = "0xB101020304"
                    let _data = string.data(using: String.Encoding.utf8)


                    self.peripheral?.writeValue(ofCharac: ser, value: _data!, completion: { (reult) in
                        switch result{
                        case .success(let value):
                            print(value)
                            print("wow")
                        case .failure(let error):
                            print("error: \(error.localizedDescription)")
                        }
                    })

Solution

  • The code you have will send the bytes that represent the string "0xB101020304", but presumably you want to send the bytes B1 01 02 03 04.

    let dataBytes:[UInt8] = [0xB1,0x01,0x02,0x03,0x04]
    
    let data = Data(bytes: dataBytes)
    
    self.peripheral?.writeValue(ofCharac: ser, value: data, completion: { (result) in
        switch result {
            case .success(let value):
                print(value)
                print("wow")
            case .failure(let error):
                print("error: \(error.localizedDescription)")
        }
    })