Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSData to NSString encoding

I have an application that receives messages from server. Those messages may contain cyrillic characters. But when I transform received data into NSString I obtain only "\u041c\u0430\u043a" symbols instead of cyrrilic ones.

   NSData *responceData = ....;

   NSString* responceString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];

How may I get correct symbols?

like image 213
Mehdzor Avatar asked Apr 13 '12 13:04

Mehdzor


People also ask

What is NSData?

NSData provides methods for atomically saving their contents to a file, which guarantee that the data is either saved in its entirety, or it fails completely. An atomic write first writes the data to a temporary file and then, only if this write succeeds, moves the temporary file to its final location.

What is NSString?

A static, plain-text Unicode string object that bridges to String ; use NSString when you need reference semantics or other Foundation-specific behavior.


1 Answers

There's a much easier solution.

If your data has literal unicode escape sequences in it (that is, \u041c\0430\043a as pure ASCII characters, with no unicode escaping applied), then this is not the UTF-8 encoding of that string. You want NSNonLossyASCIIStringEncoding.

NSData *responseData = ....;

NSString* responseString = [[NSString alloc] initWithData:responseData encoding:NSNonLossyASCIIStringEncoding];

responseString will now be exactly what you expect.

like image 170
BJ Homer Avatar answered Jan 04 '23 21:01

BJ Homer