Protobuf object data not being read in Objective C

2019-09-14 06:20发布

问题:

I use the metasyntactic classes in order to handle Google Protobuf objects in Objective C.

This works fine when making and sending protobuf objects to a server. However I am having trouble reading protobuf data that is sent back from the server which I cannot seem to parse. I use this code in the didReceiveData method:

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{

    UserId *identity = [UserId parseFromData:data];
    NSLog(@"identity firstname = %@", identity.firstName);

}

The NSLog prints out nothing and I know I have data there as when I NSLOG the data method variable I get -

<0a620a0d 12054c61 7572611a 04546573 74125108 dd4f1205 4c617572 611a0454 65737422 0a32322f 30382f32 3031322a 0032194c 61757261 2e466f72 72657374 40736973 706f7274 2e636f6d 3a0040ff ffffffff ffffffff 014a096c 61757261 74657374>

Also, when I create a protobuf object in code and access it's data property - [protobufobject data] I am able to extract information via the above method so I assume it is something in the parsing of the data that I am missing!

Any help much appreciated!

回答1:

One possible problem with your code is that the didReceiveData: can be called multiple times during one connection, so the received data could be an incomplete Protobuf object.

You should append the data to a NSMutableData object in didReceiveData:, and only parse the collected data in connectionDidFinishLoading:.