title: Swift receives data from device by BLE
body: <p>I have a device that transmits by BLE a message composed in this way: [STX]A1[ETX]</p>
  
  <p>This device use a software written in C++ and 3rd character is a boolean!</p>
  
  <p>Now, I would receive this message by iOS using swift. Other incoming message  it received correctly, but this one not.</p>
  
  <p>This is a method in C++ that trasmits:</p>
  
  <pre><code>isModeOn = (byte)data[1] == 1 ? true : false;
  
  //Send message by BLE (by Serial)
  Serial3.write(STX);
  Serial3.write(GF);
  Serial3.write(isModeOn);
  Serial3.write(ETX);
  </code></pre>
  
  <p>This is my method in swift that receives:</p>
  
  <pre><code>func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
      print(#function)
      var receivedMessage: String
  
      if characteristic.uuid == BLE_RX_UUID {
  
          receivedMessage = NSString(data: characteristic.value!, encoding: String.Encoding.utf8.rawValue)! as String
          processMessage(receivedMessage: "\(receivedMessage as String)")
      }
  }
  </code></pre>
  
  <p>Can anyone help me?</p>
  
  <p>UPDATE!
  I found this approach:</p>
  
  <pre><code>//Lettura fecilitata dei NSData
  struct DataReader {
      var data: Data
      var offset: Int = 0
  
      mutating func read() -&gt; UInt8 {
          let result = data[offset]
          offset += MemoryLayout&lt;UInt8&gt;.size
          return result
      }
      mutating func read2() -&gt; UInt16 {
          let subdata = data.subdata(in: offset..&lt;offset+MemoryLayout&lt;UInt16&gt;.size)
          let result: UInt16 = subdata.withUnsafeBytes {(bytes: UnsafePointer&lt;UInt16&gt;) in
              bytes.pointee.littleEndian
          }
          offset += MemoryLayout&lt;UInt16&gt;.size
          return result
      }
  }
  </code></pre>
  
  <p>with this I can received easely my data</p>
  
  <pre><code>var reader = MessageHelper.DataReader.init(data: receivedMessage, offset: 0)
  
      for _ in 1...reader.data.count {
          let value = reader.read()
  
          if value == STX {
              incomingMessage = ""
          } else if value == ETX {
              print(#function, incomingMessage)
              commandSelector(message: incomingMessage)
          } else {
              if value == 0x01 {
                  incomingMessage += "1"
              } else if value == 0x00 {
                  incomingMessage += "0"
              } else {
                  incomingMessage += "\(Character(UnicodeScalar(value)))"
              }
          }
      }
  </code></pre>
  
  <p>OK! And If I need to send same message</p>
  
  <pre><code>sendMessage(message: String("\(COMMAND)\(Character(UnicodeScalar(UInt8(1))))"), withResponde: true)
  </code></pre>
  
  <p>I have to convert UInt8(1) in UnicodeScalar and then Character, and that's it!</p>