I am using google protocol buffers to send some data from a C++ server to a IOS app. I use this function on the IOS side to convert the stream bytes to a string:
-(NSString*)convertStreamBytesToString:(NSMutableData*)data
{
int len = [data length];
char raw[len];
[data getBytes:raw length:len];
NSString *protocStruct =[[NSString alloc] initWithBytes:raw length:len encoding:NSUTF8StringEncoding];
return protocStruct;
}
My problem is that sometimes this doesn't work. I can see that I send and receive all the bytes, but when converting some of them are lost. So for example I get 83 bytes, but when printing the string I get about 20 characters. Where are the rest ? Is there a problem I don't know about this converting method ?
NSString is a class for handling Unicode strings. You cannot store arbitrary bytes in it as with a C string. (And even then you probably cannot transmit binary data in place of a character string and expect it to survive the transport)
You will need to convert your binary data to a string in a way that results in a valid text string. For example via Base64 encoding.
There are lots of iOS projects you can get to encode/decode Base64, just google it.
Here's an article about it: http://www.cocoawithlove.com/2009/06/base64-encoding-options-on-mac-and.html?m=1
Allocating C array on stack in obj-c causes error sometimes. Try to use dynamic memory for char array:
char* raw = (char*)malloc(len*sizeof(char));
And free it afterwards:
free(raw);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.