Question

I try to get an NSString from NSData but I get a nil value. This is my code:

NSString *dataString = [[NSString alloc] initWithData:self.message.data encoding:NSUTF8StringEncoding];

When I log self.message.data I get:

Printing description of self->_message->_data:
<OS_dispatch_data: data[0x17e48290] = { leaf, size = 331233, buf = 0x3aac000 }>

That means my data is not nil…

Can anyone help?

Was it helpful?

Solution

As answer to your question in comments: OS_dispatch_data is dispatch_data_t which has toll-free bridging with NSData on iOS 7 and Mavericks. You can simply cast it to NSData *.

So, in your case you can write:

NSData *dataCast = self.message.data;
NSString *dataString = [[NSString alloc] initWithData:dataCast encoding:NSUTF8StringEncoding];

And now you get the correct string!

In my case it appeared, when AFNetworking cast internal NSMutableData to NSData.

And this simple cast helps me.


UPD: As @Daij-Djan mentioned: If it's not works - try to check your text encoding.

For example if you're yousing NSURLSessionTask:

NSURLSessionTask *task; // Your NSURLSessionTask
NSString *encoding = [[task response] textEncodingName];

In your case (NSUTF8StringEncoding) it should be "utf-8".

OTHER TIPS

Try UTF-16 encoding instead. It may be an error converting to UTF-8 if any data in there is not recognized.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top