Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert NSData to NSString

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.

like image 381
Nirav Bhatt Avatar asked Jan 22 '13 10:01

Nirav Bhatt


5 Answers

Try this,

NSData *responseData; [Initialize it]
NSString *receivedDataString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; 
NSLog(@"%@",receivedDataString);
like image 175
vinothp Avatar answered Nov 20 '22 12:11

vinothp


Please try following code

NSString *string = [[[NSString alloc] initWithData: responseData.bytes encoding:NSUTF8StringEncoding] autorelease];
like image 28
Nimit Parekh Avatar answered Nov 20 '22 13:11

Nimit Parekh


You can use this code lines

NSString *str=[[NSString alloc] initWithBytes:data1.bytes length:data1.length encoding:NSUTF8StringEncoding];
like image 3
aknew Avatar answered Nov 20 '22 13:11

aknew


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.

like image 3
Nirav Bhatt Avatar answered Nov 20 '22 12:11

Nirav Bhatt


NSString  *image1Data = [[NSData dataWithData:myData] encodeBase64ForData];

But for this, you have to use NSData+Base64Additions class.

like image 2
Rahul Gupta Avatar answered Nov 20 '22 13:11

Rahul Gupta