How to Convert NSData to NSString - iphone

I know this has been asked quite before, and I already followed couple of approaches, but they don't work.
Following is what I already tried:
NSString *newStr = [NSString stringWithUTF8String:[responseData bytes]];
NSString *newStr = [NSString stringWithFormat:#"%.*s", [responseData length], [responseData bytes]];
None of them works. In 1st case, it fills newStr with null. In 2nd, it fills with junk characters. I know from debugger log (po responseData) that I get valid response which is like bbbbbb 00 bbbbbb. [server sends them as byte array]
What to do?
EDIT:
I am receiving this data from http request response - using ASIHTTPRequest library, in case anybody can help on that line.

Try this,
NSData *responseData; [Initialize it]
NSString *receivedDataString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"%#",receivedDataString);

Please try following code
NSString *string = [[[NSString alloc] initWithData: responseData.bytes encoding:NSUTF8StringEncoding] autorelease];

You can use this code lines
NSString *str=[[NSString alloc] initWithBytes:data1.bytes length:data1.length encoding:NSUTF8StringEncoding];

I am posting this for records sake because I found a duplicate and voting to close this down.
Actually what I am receiving is a stream of bytes represented as hex, and all the answers indicated do not work. Only [NSData description] gave me true data, which is something I can't use because it is intended for debugging.
Finally I tried the solution given here, and I get what I want.
Thanks to all for trying to help out.

NSString *image1Data = [[NSData dataWithData:myData] encodeBase64ForData];
But for this, you have to use NSData+Base64Additions class.

Use following way
NSString *dC_Str = [[NSString alloc] initWithData:decryPtd_data encoding:NSASCIIStringEncoding] ;

Related

iPhone: strange output when casting nsdata to nsstring

I get a NSData object in return after decrypting a payload with aes128:
NSData *returnData = [ciphertext AES128DecryptWithKey:keyData withIV:ivData];
I get the following hex output when i try to NSLog this:
<2db88b73 d84599a1 5779c736 09c975b7 92750cf2 d11cb41b 19f13781
4401bc57 b2ad96c8 402e3ccf 851c0219 00aec76b>
I then try to setting it as NSString:
[[NSString alloc] initWithData:returnData
encoding:NSUTF8StringEncoding];
When using NSLog() on the string i get "(null)" as output.
Can someone tell me why and where i should look for the problem?
Collided with the same issue some time ago, found the answer here.
If the data is not null-terminated, you should use -initWithData:encoding:
NSString* newStr = [[[NSString alloc] initWithData:theData
encoding:NSUTF8StringEncoding] autorelease];
If the data is null-terminated, you should instead use -stringWithUTF8String: to avoid the extra \0 at the end.
NSString* newStr = [NSString stringWithUTF8String:[theData bytes]];
(If you have ARC enabled, remove the -autorelease call.)

convert emojis into unicode dynamically

How should i convert the emojis into unicode and send it to server and then can decode it dynamically.
I can statically give the if condition for perticular emojis.But i want to make it dynamically.
Thanks in advance
few days ago i have same problem. i tried this its work for me :
to pass value to the server
NSData *data = [textView.text dataUsingEncoding:NSNonLossyASCIIStringEncoding];
NSString *goodValue = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
goodValue = [goodValue stringByReplacingOccurrencesOfString:#"\\" withString:#"\\\\"];
when fetch value from the server
NSString *goodValue = [StaticClass urlDecode:[dataDict objectForKey:#"comment_text"]];
NSData *newdata=[goodValue dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *mystring=[[NSString alloc] initWithData:newdata encoding:NSNonLossyASCIIStringEncoding];

Memory leak when parse JSON string using SBJSON

I am using following code to parse JSON and getting memory leak (100%) on line number 2. I don't know what is the problem, can someone help me ?
NSString *response = [request responseString];
NSMutableDictionary *responseJSON = [response JSONValue]; (100% leak)
NSString *tockenString = [responseJSON objectForKey:#"Token"];
NSString *userIDString = [responseJSON objectForKey:#"ID"];
I found the answer. Go to SBJsonParser.m function scanRestOfString and change the line
from
*o = [[NSMutableString alloc] initWithBytes:(char*)c length:len encoding:NSUTF8StringEncoding];
to
*o = [[[NSMutableString alloc] initWithBytes:(char*)c length:len encoding:NSUTF8StringEncoding] autorelease];
SBJsonParser has a like in scanRestOfString/NSMutableString. I reported the bug as well. Thank you all.
Remove those 2 autoreleases. They overrelease the objects.
I've had a similar problem but it turned out the leak was actually higher in the chain of methods, but Instruments was (mistakenly) pointing to this line. Look at the methods that store the results retrieved from this code.

NSString encoding for accents displays crazy characters

I am downloading data (text) from a server.
I have tried with both:NSISOLatin1StringEncoding and NSASCIIStringEncoding
But I keep seeing things like: {"estado":"M\u00e9xico"}
Noting that it should read México and not M\u00e9xico (with an accent over the e).
Looking online I figured that \u00e9 is in fact é link.
But the NSString is not able to interpret this and instead prints weird things on my UILabels:
I would really really appreciate your help on this.
Alsso, if you are itnerested, you can download the data from here: http://www.miorden.com/demo/iphone/estadoJSON.php
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://www.miorden.com/demo/iphone/estadoJSON.php"]];
NSString *string = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"Downloaded: %#", string);
string = [NSString stringWithContentsOfURL:[NSURL URLWithString:#"http://www.miorden.com/demo/iphone/estadoJSON.php"] encoding:NSISOLatin1StringEncoding error:nil];
NSLog(#"Downloaded: %#", string);
I have been literally trying for days and it is killing me!
Thank you so much!
That appears to be unicode, try NSUTF8StringEncoding.
The data is in JSON format, so you'll need to JSON decode it too.
For example using this: https://github.com/TouchCode/TouchJSON
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://www.miorden.com/demo/iphone/estadoJSON.php"]];
NSError *error;
NSArray *array = [[CJSONDeserializer deserializer] deserializeAsArray:data error:&error];
NSLog(#"Test: %#", [[array objectAtIndex:11] valueForKey:#"estado"]);
outputs
2011-08-11 09:35:45.742 enctest[63236:407] Test: México

iPhone encoding of non latin characters

I am trying to parse a JSON response of a GET request. When the characters, are latin no problem.
However when they are not latin the message doesn't come out correctly. I tried greek and instead of "πανος" i get "& pi; & alpha; & nu; & omicron; & sigmaf;"
The code I use for parsing the response is:
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"response %#", responseString);
// array from the JSON string
NSArray *results = [responseString JSONValue];
When I try to read the response from a website using ajax, everything is fine. The same applies when trying to send a GET request to the application servers with data from iphone. So when i transmit data to the server and read it from the website everything is fine. When i try to show the same data in the app, "Houston we have a problem".
Any clues?
EDIT: To avoid misunderstandings, it's not an issue of HTML, I just point out that for some readon utf-8 characters here are encoded correctly and automatically eg. "&pi" will be converted to "π", however objective c doesn't seem to do this on its own
There is a confusion I think.
π is an HTML entity which is unrelated to text encoding like UTF8 / Latin.
Read wikipedia for details about...
You need a parser to decode these entities like the one previously mentioned by Chiefly Izzy:
NSString+HTML category and method stringByReplacingHTMLEntities
Look at Cocoanetics NSString+HTML category and method stringByReplacingHTMLEntities method. You can find it at:
https://github.com/Cocoanetics/NSAttributedString-Additions-for-HTML/blob/master/Classes/NSString%2BHTML.m
Here's a pretty decent list of lot of HTML entities and their corresponding unicode characters.
Try to use this snippet of code:
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSString *decodedString = [NSString stringWithUTF8String:[responseString cStringUsingEncoding:[NSString defaultCStringEncoding]]];
NSLog(#"response %#", decodedString);
// array from the JSON string
NSArray *results = [decodedString JSONValue];
I have faced the same problem, but I solved it by changing the JSON parser. I have started using the SBJSONParser, and now I am getting the appropriate results. This is the code snippet, I have used
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
SBJSON *parser=[[SBJSON alloc]init];
NSArray *JSONData = (NSArray*)[parser objectWithString:returnString error:nil];