Encoding for converting between NSString to NSData and back - ios

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.

Related

want to have this string "مرحبا 😀 Hello" save it to database and display back to uilabel

I am looking for solution where i want to store English + Arabic + Emoji Character to store to Database and retrieve it back while display.
Below is the code what i have used to support Emoji, after that Arabic text is not showing.
+(NSString *)emojiToSave:(NSString *)str
{
NSData *dataForEmoji = [str dataUsingEncoding:NSNonLossyASCIIStringEncoding];
NSString *encodevalue = [[NSString alloc]initWithData:dataForEmoji encoding:NSUTF8StringEncoding];
return encodevalue;
}
+(NSString *)emojiToDisplay:(NSString *)str
{
NSData *msgData = [str dataUsingEncoding:NSUTF8StringEncoding];
NSString *goodMsg = [[NSString alloc] initWithData:msgData encoding:NSNonLossyASCIIStringEncoding];
return goodMsg;
}
Can anyone pls suggest to give support for Arabic what change i should do?
Thanks in advance.
Try convert it into base64 code, then insert base64 code to database:
//Original string to base64 string
NSString *emojiString = #"مرحبا 😀 Hello";
NSData *emojiData = [emojiString dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64String = [emojiData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
//Base64 string to original string
NSData *base64Data = [[NSData alloc] initWithBase64EncodedString:base64String options:NSDataBase64DecodingIgnoreUnknownCharacters];
NSString *originalString =[[NSString alloc] initWithData:base64Data encoding:NSUTF8StringEncoding];
NSLog(#"Result: %#",originalString);
Output:
You have to use an encoding that supports emoji and arabic characters. ASCII doesn't support that.
You should use NSUTF8StringEncoding everywhere, and you're fine.
Why are you using ASCII anyways? Why are you converting a string to an NSData and then back to NSString again? It doesn't make sense.

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.

NSString from NSData is nil

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?
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".
Try UTF-16 encoding instead. It may be an error converting to UTF-8 if any data in there is not recognized.

iOS : decode utf8 string

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

Convert NSString to UTF8String?

Currently I am download data from a server and I have this line to get that NSData into a NSString.
NSString *txt = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
How would I go from here to convert that NSString into a UTF8 string?
Thanks!
NSData *utf8Data = [txt dataUsingEncoding:NSUTF8StringEncoding];
Change NSASCIIStringEncoding to NSUTF8StringEncoding .
I ran a quick test now with some dummy data and seemed to work fine with just that one line.

Resources