0

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:@"Ê"];
Bruno Ferreira
  • 942
  • 9
  • 22
Oleg
  • 2,984
  • 8
  • 43
  • 71

3 Answers3

2
NSString* myString = [[NSString alloc] initWithData: theData 
                                           encoding: NSISOLatin1StringEncoding];
JeremyP
  • 84,577
  • 15
  • 123
  • 161
0

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.

karim
  • 15,408
  • 7
  • 58
  • 96
0

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
}
GSL
  • 23
  • 4