'How to convert Chinese Html String into NSString

For converting html string into NSString i am using below function

Code Snippet :

+(NSString *)getStringFromHtmlString:(NSString *)str
{

    NSData *stringData = [str dataUsingEncoding:NSUTF8StringEncoding];
    //NSHTMLTextDocumentType
    NSDictionary *options = @{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType};

    NSAttributedString *decodedString;
    decodedString = [[NSAttributedString alloc] initWithData:stringData
                                                     options:options
                                          documentAttributes:NULL
                                                       error:NULL];


    return decodedString.string;
}

Above method encode English text in proper format

But I want to encode Chinese text.

When Chinese string encode using above method it returns

I want proper encoding of chinese text.
enter image description here



Solution 1:[1]

You can add NSCharacterEncodingDocumentAttribute:@(NSUTF8StringEncoding) options:

NSDictionary *options = @{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute:@(NSUTF8StringEncoding)};

Hope it will work.

Solution 2:[2]

Swift Version:

let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [
    .documentType: NSAttributedString.DocumentType.html,
    .characterEncoding: String.Encoding.utf8.rawValue
]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bhakti
Solution 2 Jadian