NSMutableData to NSString - how to know which enco

2019-06-10 08:22发布

问题:

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?

回答1:

Try this.

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"%@", [response textEncodingName]);
}


回答2:

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.