简体   繁体   中英

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.
在此处输入图像描述

You can add NSCharacterEncodingDocumentAttribute:@(NSUTF8StringEncoding) options:

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

Hope it will work.

Swift Version:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM