I'm getting text from a server, the text is encoded with ISO 8859-1
.
How can I convert it to UTF-8?
Now I'm just replacing special characters like this:
text = [text stringByReplacingOccurrencesOfString:@"É" withString:@"Ê"];
I'm getting text from a server, the text is encoded with ISO 8859-1
.
How can I convert it to UTF-8?
Now I'm just replacing special characters like this:
text = [text stringByReplacingOccurrencesOfString:@"É" withString:@"Ê"];
NSString* myString = [[NSString alloc] initWithData: theData
encoding: NSISOLatin1StringEncoding];
I got the same problem.
Even if you get the data
you received is formatted in ISO Latin string,
NSString* latin1String = [[NSString alloc] initWithData:data encoding:NSISOLatin1StringEncoding];
or if the text is NSString from latin1 string,
NSData *utfData = [latin1String dataUsingEncoding:NSUTF8StringEncoding];
NSString *utf = [[NSString alloc] initWithData:utfData encoding:NSUTF8StringEncoding];
This is specially needed for NSJSONSerialization since it accept only utf8 encoded string.
For Swift 2.2
If your string is HTML encoded:
func replaceChars(htmlEncodedString: String) -> String {
do {
let encodedData = htmlEncodedString.dataUsingEncoding(NSUTF8StringEncoding)!
let attributedOptions : [String: AnyObject] = [
NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding
]
let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil)
return attributedString.string
} catch {
fatalError("Unhandled error: \(error)")
}
}
If your string is ISO 8859-1 (Latin-1) encoded:
func decodeISO88591(str:String) -> String {
if let utfData = str.dataUsingEncoding(NSISOLatin1StringEncoding) {
if let utf = String(data: utfData, encoding: NSUTF8StringEncoding) {
return utf
}
}
return str
}