Nirav Bhatt
Nirav Bhatt

Reputation: 6969

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.

Upvotes: 6

Views: 25473

Answers (6)

Nag Raj
Nag Raj

Reputation: 888

Use following way

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

Upvotes: 1

Rahul Gupta
Rahul Gupta

Reputation: 808

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

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

Upvotes: 2

Nirav Bhatt
Nirav Bhatt

Reputation: 6969

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.

Upvotes: 3

vinothp
vinothp

Reputation: 10059

Try this,

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

Upvotes: 13

aknew
aknew

Reputation: 1121

You can use this code lines

NSString *str=[[NSString alloc] initWithBytes:data1.bytes length:data1.length encoding:NSUTF8StringEncoding];

Upvotes: 3

Nimit Parekh
Nimit Parekh

Reputation: 16864

Please try following code

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

Upvotes: 3

Related Questions