Swift将UTF16转换为UTF8并返回

时间:2016-03-01 02:21:22

标签: swift utf-8 utf-16 string-conversion

我正在Swift构建一个应用程序,我正在使用Backendless作为我的后端。原来他们的数据库是UTF8,因此我不能在不首先转换String的情况下保存emojis。 我似乎无法找到将此转换为UTF8的正确方法。我试过这个:

let encoding = processedText.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)

但是在这个操作之后,表情符号看起来像这样: %F0%9F%99%84%F0%9F%98%80%F0%9F%98%92%F0%9F%98%89%F0%9F%98%B6%F0%9F%98%B6%F0 %9F%98%80%F0%9F%99%81

我试过这个:     class func stringToUTF8String(string:String) - >串? {

    let encodedData = string.dataUsingEncoding(NSUTF8StringEncoding)!
    let attributedOptions = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
    do{
    let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil)
    return attributedString.string
    }catch _ {
    }

    return nil
}

表情符号看起来像这样: 🤔🤔 DY“... DY™ðŸ~,ðŸ~ðŸ~ŽðŸ~‰ðŸ~...ðŸ~‰

有没有人有任何建议?感谢

1 个答案:

答案 0 :(得分:2)

首先,要使用utf8编码从String创建NSData,请使用

String(data: theData, encoding: NSUTF8StringEncoding)

其次,swift String已经符合unicode标准。您不必像他们已经那样转换它们。您可以使用各自的属性访问不同的编码,例如String.utf8String.utf16等等。

第三,要正确使用NSAttributedString,utf8会根据数据对您的字符串进行编码,您必须将NSCharacterEncodingDocumentAttribute密钥添加到attributedOptions字典,其值为NSUTF8StringEncoding

最后的注释,我不知道这是否是一个部分方法,但是不应该仅使用属性字符串来编码字符串。

这是NSAttributedString以某种格式编码返回乱码的数据。 enter image description here

这是NSAttributedString将数据编码为utf8并返回正确的文本。 enter image description here

这里将字符串编码为utf8字符串。 enter image description here

我知道这是一张图片,但我想要显示结果。如果这些不起作用,数据库可能正在剥离位。哪个很糟糕,也不知道该怎么做,如果你想要unicode支持,你可能不应该使用那个数据库。