Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert UTF-8 encoded NSData to NSString

I have UTF-8 encoded NSData from windows server and I want to convert it to NSString for iPhone. Since data contains characters (like a degree symbol) which have different values on both platforms, how do I convert data to string?

like image 384
Ashwini Shahapurkar Avatar asked Mar 18 '10 06:03

Ashwini Shahapurkar


1 Answers

If the data is not null-terminated, you should use -initWithData:encoding:

NSString* newStr = [[NSString alloc] initWithData:theData encoding:NSUTF8StringEncoding]; 

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

(Note that if the input is not properly UTF-8-encoded, you will get nil.)


Swift variant:

let newStr = String(data: data, encoding: .utf8) // note that `newStr` is a `String?`, not a `String`. 

If the data is null-terminated, you could go though the safe way which is remove the that null character, or the unsafe way similar to the Objective-C version above.

// safe way, provided data is \0-terminated let newStr1 = String(data: data.subdata(in: 0 ..< data.count - 1), encoding: .utf8) // unsafe way, provided data is \0-terminated let newStr2 = data.withUnsafeBytes(String.init(utf8String:)) 
like image 174
kennytm Avatar answered Sep 18 '22 13:09

kennytm