[iphone] Converting NSData to NSString in Objective c

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.

This question is related to iphone objective-c ios ipad

The answer is


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
};

Swift:

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

or .utf8 or whatever encoding appropriate


NSString *string = [NSString stringWithUTF8String:[Data bytes]];

in objective C:

NSData *tmpData;
NSString *tmpString = [NSString stringWithFormat:@"%@", tmpData];
NSLog(tmpString)

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


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];

Objective C:

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

Swift:

let str = String(data: data, encoding: .ascii)

Use below code.

NSString* myString;
myString = [[NSString alloc] initWithData:nsdata encoding:NSASCIIStringEncoding];

-[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).


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];

Examples related to iphone

Detect if the device is iPhone X Xcode 8 shows error that provisioning profile doesn't include signing certificate Access files in /var/mobile/Containers/Data/Application without jailbreaking iPhone Certificate has either expired or has been revoked Missing Compliance in Status when I add built for internal testing in Test Flight.How to solve? cordova run with ios error .. Error code 65 for command: xcodebuild with args: "Could not find Developer Disk Image" Reason: no suitable image found iPad Multitasking support requires these orientations How to insert new cell into UITableView in Swift

Examples related to objective-c

Adding a UISegmentedControl to UITableView Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Warp \ bend effect on a UIView? Use NSInteger as array index Detect if the device is iPhone X Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3 ITSAppUsesNonExemptEncryption export compliance while internal testing? How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem? Change status bar text color to light in iOS 9 with Objective-C

Examples related to ios

Adding a UISegmentedControl to UITableView Crop image to specified size and picture location Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Autoresize View When SubViews are Added Warp \ bend effect on a UIView? Speech input for visually impaired users without the need to tap the screen make UITableViewCell selectable only while editing Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

Examples related to ipad

What is correct media query for IPad Pro? iPad Multitasking support requires these orientations How to restrict UITextField to take only numbers in Swift? How to present a modal atop the current view in Swift Presenting a UIAlertController properly on an iPad using iOS 8 Detect current device with UI_USER_INTERFACE_IDIOM() in Swift HTML5 Video tag not working in Safari , iPhone and iPad Install .ipa to iPad with or without iTunes How to hide UINavigationBar 1px bottom line How to fix UITableView separator on iOS 7?