Ashwini Ashwini -5 years ago 394
iOS Question

Convert UTF-8 encoded NSData to NSString

I have UTF-8 encoded

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

Answer Source

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

Swift variant:

let newStr = String(data: data, encoding: NSUTF8StringEncoding)
// note that `newStr` is a `String?`, not a `String`.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download