0

I have an app that pulls data from a socket using the Stream class.

Everything appears to work as expected, I am receiving data in the delegate method:

func stream(_ Stream: Stream, handle eventCode: Stream.Event)

The challenge I am having is converting the data into useful information. There is an Android app that does what I am trying to accomplish using a ByteBuffer.

This ByteBuffer iterates through the data at intervals of 4 and parses the data into the required data types using methods like getFloat and getInt.

Basically I want to loop through the InputStream data and retrieve all the values in the stream. Each value is always 4 bytes in length.

How can I do this using Swift 3?

Harjot Singh
  • 438
  • 6
  • 19
Buyin Brian
  • 2,626
  • 2
  • 24
  • 42

1 Answers1

1

I got it working. If anyone else needs to do something similar, here is my code:

func stream(_ aStream: Stream, handle eventCode: Stream.Event) {

    if aStream === inputStream {
        switch eventCode {
        case Stream.Event.errorOccurred:
            print("input: ErrorOccurred: \(String(describing: aStream.streamError))")
        case Stream.Event.openCompleted:
            print("input: OpenCompleted")
        case Stream.Event.hasBytesAvailable:
            print("input: HasBytesAvailable")
            var index = 0 //this index is used to map the value from bytes below. For example, 0 is date
            var buffer = [UInt8](repeating: 0, count: 4) //this breaks the bytes into groups of 4 bytes each
            while (inputStream?.hasBytesAvailable)!{
                if let length = inputStream?.read(&buffer, maxLength: buffer.count) {
                    if(length > 0){
                        let data = Data(bytes: buffer)
                        let UINT32 = UInt32(littleEndian: data.withUnsafeBytes { $0.pointee })
                let float =  data.withUnsafeBytes { $0.pointee } as Float
                        let int = data.withUnsafeBytes { $0.pointee } as Int
            //Do something with the values, map to an object, etc   
                        index += 1 //increase the index to know what the next 4 bytes should be mapped as
                    }
                }
            }

            break

        default:
            break
        }
    } ...
Buyin Brian
  • 2,626
  • 2
  • 24
  • 42