Decode Protobuf in binary format using Swift

1k views Asked by At

I am new to Protobuf & I want to decode protobuf(syntax 2 type) in swift. Below I am sharing library that i am using in swift

'SwiftProtobuf'

I have one proto type file and with the help of compiler i have generated one proto.pb.swift file and added it to project

Step 1: I am receiving protobuf data in my app and but I am unable to decode this message.

I have used below code :

// Deserialize a received Data object from `binaryData`
let decodedInfo = try User(serializedData: bytesReceived)

Below is the link i am following https://medium.com/@dzungnguyen.hcm/protobuf-in-swift-809658ecdb22

Moving forward, I passed partial == true then i am able to get the User data but all its values are garbages for eg: time = -1532154564212 some thing like this

So I thought to check its bytes data for this i have used below lines of codes

let array = bytesReceived.withUnsafeBytes {
                [UInt8](UnsafeBufferPointer(start: $0, count: bytesReceived.count))
            }

Below is the value of array

[122, 43, 10, 10, 8, 128, 192, 4, 16, 128, 128, 160, 140, 6, 21, 165, 165, 165, 165, 24, 143, 255, 255, 255, 15, 32, 172, 255, 255, 255, 15, 40, 129, 8, .... 160, 140]

One of my python developer friend have already decoaded protobuf message below i am sharing his Python code

data = bytearray(proto_data)
 length, pos = 0, 0

    # 
    while pos < len(data):
        msg = Myproto.User()              
        # find the position and length of submessage
        length, pos = _DecodeVarint32(data, pos)

        try:
            msg.ParseFromString(data[pos:(pos + length)])
        except:
            pass

        pos += length
        print("Msg: ", msg)

Also

msg.ParseFromString(data[pos:(pos + length)])

I am not getting what exactly ParseFromString method does in python

Please help me how can we decode this protobuf message In Swift. Thanks In Advance

0

There are 0 answers