我有一个方法可以用来将HTML文本转换为普通文本。
问题是,当我传递HTML文本时,它会给普通文本增加一个额外的回车。
下面是导致问题的方法和示例文本。
有人能让我知道我错过了什么或者需要为此做些什么吗?
谢谢你的帮助。
- (NSString *)flattenHTML {
NSString *finalString = self;
if ([self isEqualToString:kSNREmptyString] == NO) {
NSAttributedString *attributeString = nil;
NSData *data = [self dataUsingEncoding:NSUnicodeStringEncoding];
if (nil != data) {
NSDictionary *encodingDict = [NSDictionary dictionaryWithObject:@(NSUnicodeStringEncoding)
forKey:@"CharacterEncoding"];
attributeString = [[NSAttributedString alloc] initWithHTML:data
documentAttributes:&encodingDict];
finalString = [attributeString string];
}
}
return finalString;
}
示例文本:
Lorem ipsum dolor sit amet,consectetur adipiscing elit,sed do eusmod tempor incidunt ut labore et dolore magna aliqua.Excepteur sint occaecat cupidatat non proident,sunt in culpa qui configutia deserunt mollit anim id est laborum.
Lorem ipsum dolor sit amet,consectetur adipiscing elit,sed do eusmod tempor incidunt ut labore et dolore magna aliqua.Excepteur sint occaecat cupidatat non proident,sunt in culpa qui configutia deserunt mollit anim id est laborum.
Lorem ipsum dolor sit amet,consectetur adipiscing elit,sed do eusmod tempor incidunt ut labore et dolore magna aliqua.Excepteur sint occaecat cupidatat non proident,sunt in culpa qui configutia deserunt mollit anim id est laborum.
Lorem ipsum dolor sit amet,consectetur adipiscing elit,sed do eusmod tempor incidunt ut labore et dolore magna aliqua.Excepteur sint occaecat cupidatat non proident,sunt in culpa qui configutia deserunt mollit anim id est laborum.
Lorem ipsum dolor sit amet,consectetur adipiscing elit,sed do eusmod tempor incidunt ut labore et dolore magna aliqua.Excepteur sint occaecat cupidatat non proident,sunt in culpa qui configutia deserunt mollit anim id est laborum.
Lorem ipsum dolor sit amet,consectetur adipiscing elit,sed do eusmod tempor incidunt ut labore et dolore magna aliqua.Excepteur sint occaecat cupidatat non proident,sunt in culpa qui configutia deserunt mollit anim id est laborum.
Lorem ipsum dolor sit amet,consectetur adipiscing elit,sed do eusmod tempor incidunt ut labore et dolore magna aliqua.Excepteur sint occaecat cupidatat non proident,sunt in culpa qui configutia deserunt mollit anim id est laborum.
也许,这段代码对你有帮助,它在这里工作得很好。检查它下面的代码。
- (void)viewDidLoad
{
[super viewDidLoad];
[self HtmltoText]
}
-(void)HtmltoText
{
NSString *Html_Str =[NSString stringWithFormat:@"<html><head>
<title>My First HTML</title></head><body>
<p>The HTML head element contains meta data.</p>
<p>Meta data is data about the HTML document. <br/>
Break Next line.</p></body> </html>"];
NSAttributedString *attributedString = [[NSAttributedString alloc]
initWithData: [Html_Str
dataUsingEncoding:NSUnicodeStringEncoding]
options: @{
NSDocumentTypeDocumentAttribute:
NSHTMLTextDocumentType }
documentAttributes: nil
error: nil
];
NSLog(@"Html To Normal %@ ",attributedString );
}