有时候有这样的需求,需要把网页的内容显示到uilabel或UITextView中,有同学就会想到使用ono或hpple配合xPath解析html;
步骤较复杂,这里我提供一个非常简便的方法:
AFHTTPSessionManager *manager =[AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSString*urlStr = @"https://www.baidu.com";
[manager GET:urlStr parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
//通过afn获取网页内容
NSString *result = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[result dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];//将网页内容格式化
_label.attributedText = attrStr;//_label是UILabel
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(@"%@",error);
}];