swift UTF8 encoding and non UTF8 character

2019-01-27 02:42发布

问题:

i've a some text from json file, in this text i've applied utf8 encode but this encoder don't recognize a non standard character àèìòù and it's capital char, there is a method to purify ma string ? here my func

func stringToUTF8String (stringaDaConvertire stringa: String) -> String {

let encodedData = stringa.dataUsingEncoding(NSUTF8StringEncoding)!
let attributedOptions = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
let attributedString = NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil, error: nil)!
//println(attributedString.string)
return attributedString.string

}

thank's

回答1:

i've found solution, the utf8 take 8bit of table ascii, and the utf16 take 16bit ascii table, the solution is simple by modifing my func in

func stringToUTF16String (stringaDaConvertire stringa: String) -> String {

let encodedData = stringa.dataUsingEncoding(NSUTF16StringEncoding)!
let attributedOptions = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
let attributedString = NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil, error: nil)!
//println(attributedString.string)
return attributedString.string
}

simple ad functional