Convert NSString to UTF8String? - ios

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.

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.

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.

responseString is null

my webservice returns json string with new lines so It causes problem that responseString gives always null.
NSString *responseString=[[NSString alloc] initWithData:kampanyadata encoding:NSUTF8StringEncoding];
NSLog(#"%#",[NSString stringWithFormat:#"responsestring:%#",responseString]);
----responsestring:null
how can I replaces new lines character in JSON String?
NSString *tempString = [tempString stringByReplacingOccurrencesOfString:#"\n" withString:#" "];
I think you need to do this :)
Are you sure kampanyadata is not null? If it's not null try to use NSASCIIStringEncoding like this:
NSString *responseString=[[NSString alloc] initWithData:kampanyadata encoding:NSASCIIStringEncoding];.
Offtopic
And btw the NSLog(); method takes a NSString formatted already as parameter so you can use:
NSLog(#"responsestring:%#",responseString);
soapResults = [[NSString alloc]
initWithBytes: [webData mutableBytes]
length:[webData length]
encoding:NSUTF8StringEncoding];
try this this works fine for me
You got some NSData, and you tried to convert it to an NSString. There's no JSON involved at this point. Any errors have nothing to do with JSON or newline characters whatsoever. Possibilities: 1. The NSData that you received is nil. 2. The NSData that you received isn't in UTF-8 format.
Your NSLog statement is quite funny. Look at the definition of NSLog - the first parameter is a format string. Instead of
NSLog(#"%#",[NSString stringWithFormat:#"responsestring:%#",responseString]);
you should write
NSLog (#"responseString:%#", responseString);
And you can pass the JSON document directly to NSJSONSerializer. No need to convert it to an NSString. Actually, if the data is large, just a waste of valuable memory.

Resources