ios將html的內容顯示在uiLabel或UITextView中

有時候有這樣的需求,需要把網頁的內容顯示到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);
    }];

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章