NSMutableData to NSString - how to know which enco

2019-06-10 07:55发布

I'm using Google Protobuf to send a serialized class to an http server. The command to do this is:
message.SerializeToString(&out); Notice that we are serializing to a String. The server returns the exact same object back to me.

So, in my connection: didReceiveData method, I am getting data.

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data
{
    if (self.receivingData) {
        [self.dataReceived appendData:data];
    }
}

In my connectionDidFinishLoading method I think I need to put the NSMutableData (self.dataReceived) into an NSString.

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    self.receivingData = NO;
    NSLog(@"%@", self.dataReceived);

    NSString *data = [[NSString alloc] initWithData:self.dataReceived encoding:NSASCIIStringEncoding];  // Wrong encoding ????

    NSMutableDictionary *processedData = [NSMutableDictionary dictionaryWithCapacity:1];
    [processedData setObject:data forKey:@"ImageData"];

    NSNotificationCenter *processedNote = [NSNotificationCenter defaultCenter];
    [processedNote postNotificationName:@"DataReceived" object:nil userInfo:processedData];
}

But I'm not sure what encoding to use. When I send the data, it looks like this:

"\b\x01\x12\x04Lucy\x1a\xd4\xdc;\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\...... (There's more)

When I receive the data, it looks like this:

<08011204 4c756379 1ad4dc3b ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ..... (There's more)

When I init the NSString with data above (encoding NSASCIIStringEncoding), I get this:

LucyÔÜ;ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ ....... (There's more)

Ultimately, I will need to parse the data from a string using the Google Protobuf method: message.ParseFromString(data);

How can I know which encoding to use?

2条回答
对你真心纯属浪费
2楼-- · 2019-06-10 08:38

Try this.

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"%@", [response textEncodingName]);
}
查看更多
Animai°情兽
3楼-- · 2019-06-10 08:47

I ended up using the following code:

    const char *bytes = (const char *)[data bytes];
    std::string byteString = std::string(bytes);

That worked!!

But @trick14 had a cool answer that shows the encoding type. That was awesome.

I hope this helps somebody.

查看更多
登录 后发表回答