1. 官方方法
1.1 HTML String => NSAttributedString
- (nullable NSAttributedString *)getAttributedStringFromHTMLString:(NSString *)string
{
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *options = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)};
if (data)
{
return [[NSAttributedString alloc] initWithData:data options:options documentAttributes:nil error:nil];
}
return nil;
}
PS: 这个方法会丢失 HTML String 中删除线的样式
1.2 NSAttributedString => HTML String
- (nullable NSString *)getHTMLStringFromAttributedString:(NSAttributedString *)attributedString
{
NSDictionary *documentAttributes = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType};
NSData *data = [attributedString dataFromRange:NSMakeRange(0, attributedString.length) documentAttributes:documentAttributes error:NULL];
if (data)
{
return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}
return nil;
}
2. DTCoreText
为了解决删除线信息在转换过程中丢失的问题,我们改用了 DTCoreText。