Olga Dalton
Olga Dalton

Reputation: 849

Change data encoding

I get some data from the server in Unicode. However I need this data in UTF8. How can I convert data to UTF8 encoding?

Upvotes: 0

Views: 696

Answers (2)

Peter Hosey
Peter Hosey

Reputation: 96333

The ideal solution is that that the server sends you UTF-8 in the first place.

UTF-8 is an encoding of Unicode, so depending on what you mean by “Unicode” in your question, it may already be doing that.

Cocoa misuses “Unicode” in the symbol NSUnicodeStringEncoding to refer to UTF-16. It's possible, but unlikely, that that's what the server is sending you.

The server should tell you in the Content-Type header what encoding it used for the content. You should look at that in your program rather than assuming the server will use any specific encoding.

If the encoding is not specified in the header, try treating it as UTF-8, and if that doesn't work, I suggest complaining to whoever runs the server.

To convert from any encoding supported by Cocoa to UTF-8, pass the input data and the encoding it's in to the -[NSString initWithData:encoding:] method, which will decode the data and produce a string; then, send the string a dataUsingEncoding: message with NSUTF8StringEncoding as the desired encoding.

Upvotes: 1

amrox
amrox

Reputation: 6247

Well UTF-8 is an encoding for Unicode, but to get a string:

NSString *string = [[NSString alloc] initWithData:yourData encoding:NSUTF8StringEncoding]

Upvotes: 1

Related Questions