92

I want to convert NSData to NSString..What is the best way to do this?

I am using this code but the final string returns null

NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@",str);

When I see console It will print null.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Mehul Mistri
  • 15,037
  • 14
  • 70
  • 94
  • @Nik.... @Marvin: Are you the same person or from within the same lan? I just wonder, why your [identicons](http://stackoverflow.com/questions/392280/what-is-the-algorithm-used-to-generate-those-little-gravatar-identicon-images/392288#392288) are exactly the same. – vikingosegundo Jun 20 '11 at 13:49
  • What's the string? If you're getting `nil` then I guess your data isn't a valid utf8 string? – deanWombourne Jun 20 '11 at 13:49
  • @vikingosegundo For your kind information i don't know nik... – Mehul Mistri Jun 21 '11 at 04:04
  • that is really funny, as it is extremely unlikely. but still possible. – vikingosegundo Jun 21 '11 at 07:19

10 Answers10

100

Use below code.

NSString* myString;
myString = [[NSString alloc] initWithData:nsdata encoding:NSASCIIStringEncoding];
Jhaliya - Praveen Sharma
  • 31,697
  • 9
  • 72
  • 76
48

The docs for NSString says

https://developer.apple.com/documentation/foundation/nsstring/1416374-initwithdata

Return Value An NSString object initialized by converting the bytes in data into Unicode characters using encoding. The returned object may be different from the original receiver. Returns nil if the initialization fails for some reason (for example if data does not represent valid data for encoding).

You should try other encoding to check if it solves your problem

 // The following constants are provided by NSString as possible string encodings.
enum {
   NSASCIIStringEncoding = 1,
   NSNEXTSTEPStringEncoding = 2,
   NSJapaneseEUCStringEncoding = 3,
   NSUTF8StringEncoding = 4,
   NSISOLatin1StringEncoding = 5,
   NSSymbolStringEncoding = 6,
   NSNonLossyASCIIStringEncoding = 7,
   NSShiftJISStringEncoding = 8,
   NSISOLatin2StringEncoding = 9,
   NSUnicodeStringEncoding = 10,
   NSWindowsCP1251StringEncoding = 11,
   NSWindowsCP1252StringEncoding = 12,
   NSWindowsCP1253StringEncoding = 13,
   NSWindowsCP1254StringEncoding = 14,
   NSWindowsCP1250StringEncoding = 15,
   NSISO2022JPStringEncoding = 21,
   NSMacOSRomanStringEncoding = 30,
   NSUTF16StringEncoding = NSUnicodeStringEncoding,
   NSUTF16BigEndianStringEncoding = 0x90000100,
   NSUTF16LittleEndianStringEncoding = 0x94000100,
   NSUTF32StringEncoding = 0x8c000100,
   NSUTF32BigEndianStringEncoding = 0x98000100,
   NSUTF32LittleEndianStringEncoding = 0x9c000100,
   NSProprietaryStringEncoding = 65536
};
Cœur
  • 37,241
  • 25
  • 195
  • 267
Felipe Sabino
  • 17,825
  • 6
  • 78
  • 112
17

-[NSString initWithData:encoding] will return nil if the specified encoding doesn't match the data's encoding.

Make sure your data is encoded in UTF-8 (or change NSUTF8StringEncoding to whatever encoding that's appropriate for the data).

Morten Fast
  • 6,322
  • 27
  • 36
  • I converted an image into the NSdata and again converting the NSdata into the String using the NSUTF8StringEncoding. But it is showing nil. – Ramakrishna Oct 08 '16 at 06:06
6

Objective C:

[[NSString alloc] initWithData:nsdata encoding:NSASCIIStringEncoding];

Swift:

let str = String(data: data, encoding: .ascii)
Alexander Volkov
  • 7,904
  • 1
  • 47
  • 44
5
NSString *string = [NSString stringWithUTF8String:[Data bytes]];
Nag Raj
  • 880
  • 1
  • 12
  • 18
2

-[NSString initWithData:encoding] is your friend but only when you use a proper encoding.

DD_
  • 7,230
  • 11
  • 38
  • 59
Bilal Khan
  • 63
  • 6
1

Swift:

let jsonString = String(data: jsonData, encoding: .ascii)

or .utf8 or whatever encoding appropriate

Jess
  • 1,394
  • 12
  • 12
1

Unsure of data's encoding type? No problem!

Without need to know potential encoding types, in which wrong encoding types will give you nil/null, this should cover all your bases:

NSString *dataString = [data base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithCarriageReturn];

Done!




Note: In the event this somehow fails, you can unpack your NSData with NSKeyedUnarchiver , then repack the (id)unpacked again via NSKeyedArchiver, and that NSData form should be base64 encodeable.

id unpacked = [NSKeyedUnarchiver unarchiveObjectWithData:data];
data = [NSKeyedArchiver archivedDataWithRootObject:unpacked];
Community
  • 1
  • 1
Albert Renshaw
  • 17,282
  • 18
  • 107
  • 195
0

Objective C includes a built-in way to detect a the encoding of a string embedded in NSData.

NSData* data = // Assign your NSData object...

NSString* string;
NSStringEncoding encoding = [NSString stringEncodingForData:data encodingOptions:nil convertedString:&string usedLossyConversion:nil];
Andrew Rondeau
  • 667
  • 7
  • 18
-2

in objective C:

NSData *tmpData;
NSString *tmpString = [NSString stringWithFormat:@"%@", tmpData];
NSLog(tmpString)
Ashok R
  • 19,892
  • 8
  • 68
  • 68
  • this one is wrong, it will return something like ```{length = XX, bytes = 0xYYYYYYYY}``` and I assume question was how to unwrap encoded string from raw bytes, not their description – raistlin Apr 09 '20 at 14:06