iOS : decode utf8 string - ios

I'm receiving a json data from server with some strings inside. I use SBJson https://github.com/stig/json-framework to get them.
However when I output some strings at UILabel they look like this: \u0418\u043b\u044c\u044f\u0411\u043b\u043e\u0445 (that's Cyrillic symbols)
And it's all right with latin characters
How can I decode it into normal symbols?
Some code about getting data:
NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *stringData = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *object = [parser objectWithString:stringData error:nil];
NSString *comments = [NSString stringWithFormat:#"%#",[object valueForKey:#"comments"]];
String comments has a very special format, so I'm doing some operation like stringByTrimmingCharactersInSet ,
stringByReplacingOccurrencesOfString ,
NSArray* json_fields = [comments_modified componentsSeparatedByString: #";"];
to get a final data.
This is an example of received data after some trimming/replacing (it's NSString* comments):
"already_wow"=0;"date_created"="2012/03/1411:11:18";id=41598;name="\U0418\U043b\U044c\U044f\U0411\U043b\U043e\U0445";text="\U0438\U043d\U0442\U0435\U0440\U0435\U0441\U043d\U043e";"user_id"=1107;"user_image"="user_image/a6/6f/96/21/20111220234109510840_1107.jpg";"user_is_deleted"=0;username=IlyaBlokh;"wow_count"=0;
You see that fields text and name are encoded
If I display them on the view (at UILabel for example), they still look the same

maybe the string returned is just the unicode string representation (ascii string), that's means not returned the content encoded with utf8, to try this with NSASCIIStringEncoding to get stringData

Related

unable to show emoji's properly in UIlabel

I am trying to save the emojis to server and on later time receiving them.
I used the Following Code before
NSData *data = [strEmo dataUsingEncoding:NSNonLossyASCIIStringEncoding];
NSString *goodValue = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSData *data1 = [strEmo dataUsingEncoding:NSUTF8StringEncoding];
NSString *goodValue = [[NSString alloc] initWithData:data encoding:NSNonLossyASCIIStringEncoding];
It generates the Hashcode for the Emoji. But decoding doesn't work. So I skipped the Idea of using this Code.
Then I used a third Party NSString+HTML.h Class. Which Sends and recieve emoji easily. But
Now the Problem is when there are so many emoji's the UIlabel on which I am showing the data, the emojis are distorted and If I saved 20 emojis it shows 12-13 only.
I have added the Pic for reference
where Yellow part is UIlabel with back colored Yellow
Buddy why are you changing the string in Data two times in a row just simply use this
NSString *uniText = [NSString stringWithUTF8String:[strEmo UTF8String]];
NSData *msgData = [uniText dataUsingEncoding:NSNonLossyASCIIStringEncoding];
NSString *readyString = [[NSString alloc] initWithData:msgData encoding:NSUTF8StringEncoding];
First convert your string into constant C characters then convert it into string using UTF8 encoding, now convert it into NSData as (7-bit verbose ASCII to represent all Unicode characters) using NSNonLossyASCIIStringEncoding encoding and then again string ready to send with unicode characters. Hope this should work as it is working fine in my code.

A string encoding issuse on IOS

I came across a problem with string encoding in ios development. The story is as below:
I create some values in Chinese and then create a NSDictionary for those values, the dictionary is used as parameter for network request:
- (void)createActivity
{
NSString *actionTheme = titleF.text;
NSString *actionTitle = biaotiF.text;
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:actionTheme, #"actionTheme", actionTitle, #"actionTitle",nil];
[self networkrequest:];
}
Then some work has been done for the dictionary:
Transform the dictionary to the form of JSON as the type of NSString.
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:param options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
Encoding the string , because of Chinese word in the string.
NSString *urlEncodedString = [jsonString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
At last a full url was create with the string above:
http://app.ic100.com/action/add?paramJson=%7B%22actionTheme%22%3A%22%E6%88%96%E8%80%85%E5%92%8C%E7%94%9F%E6%B4%BB%22%2C%22actionSite%22%3A%22%E5%8E%A (something like this)
I use the third party "ASIFormDataRequest" for network request, and I also set the StringEncoding:
ASIFormDataRequest *requstHttp = [[ASIFormDataRequest alloc] init];
[requstHttp setStringEncoding:NSUTF8StringEncoding];
....
All the datas has been sent to the server successfully, but when I request these data from the server and show then on the iphone. It turn to be unreadable text:
I have carefully checked all the place that I should encode or decode the string, and only utf8 is used. What`s more , for the server side , no other encoding used either. And my colleague has tested sent data from Android platform, no problem. So I think maybe I have missed some points.
Any advise?
By using the class Base64 you can encode or decode the string.
Add Base64 class in your project from HERE
see the mehode in class to encode.
Encode:
+ (NSString *)stringWithBase64EncodedString:(NSString *)string;
- (NSString *)base64EncodedString;
Decode:
- (NSString *)base64DecodedString;

Encoding for converting between NSString to NSData and back

I'm trying to encrypt/decrypt an NSString and return the original string in the end. Here's how I convert the string to a data object:
NSData *string_data = [string dataUsingEncoding:NSUTF8StringEncoding];
And after that data has been encrypted/decrypted I want it back to the original string by doing:
NSString *to_string = [NSString stringWithCString:[decrypted_data bytes] encoding:NSUTF8StringEncoding];
The encoding seems to match, but I still get a null when I try to print out to_string to the console. I've tried all sorts of encoding settings. It doesn't seem to work.
Use:
NSString *to_string = [[NSString alloc] initWithData:string_data encoding:NSUTF8StringEncoding];
It is not safe to use stringWithCString because the bytes buffer you get from NSData is not guaranteed to be null-terminated.

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?
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.

Encrypted twitter feed

I'm developing an iOS application , that will take a twits from twitter,
I'm using the following API
https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&count=2&screen_name=TareqAlSuwaidan
The problem are feed in Arabic Language ,
i.e the text feed appears like this
\u0623\u0646\u0643 \u0648\u0627\u0647\u0645
How can i get the real text (or how to encode this to get real text) ?
This is not encrypted, it is unicode. The codes 0600 - 06ff is Arabic. NSString handles unicode.
Here is an example:
NSString *string = #"\u0623\u0646\u0643 \u0648\u0627\u0647\u0645";
NSLog(#"string: '%#'", string);
NSLog output:
string: 'أنك واهم'
The only question is exactly what problem are you seeing, are you getting the Arabic text? Are you using NSJSONSerialization to deserialize the JSON? If so there should be no problem.
Here is an example with the question URL (don't use synchronous requests in production code):
NSURL *url = [NSURL URLWithString:#"https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&count=2&screen_name=TareqAlSuwaidan"];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error;
NSArray *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
NSDictionary *object1 = [jsonObject objectAtIndex:0];
NSString *text = [object1 objectForKey:#"text"];
NSLog(#"text: '%#'", text);
NSLog output:
text: '#Naser_Albdya أيدت الثورة السورية منذ بدايتها وارجع لليوتوب واكتب( سوريا السويدان )
Those are Unicode literals. I think all that's needed is to use NSString's stringWithUTF8String: method on the string you have. That should use NSString's native Unicode handling to convert the literals to the actual characters. Example:
NSString *directFromTwitter = [twitterInterface getTweet];
// directFromTwitter contains "\u0623\u0646\u0643 \u0648\u0627\u0647\u0645"
NSString *encodedString = [NSString stringWithUTF8String:[directFromTwitter UTF8String]];
// encodedString contains "أنك واهم", or something like it
The method call inside the conversion call ([directFromTwitter UTF8String]) is to get access to the raw bytes of the string, that are used by stringWithUTF8String. I'm not exactly sure on what those code points come out to, I just relied on Python to do the conversion.

Resources