NSURLSession加载网络HTML数据

#import "ViewController.h"

#import "Masonry.h"


#define topMargin 0

#define leftMargin 0

#define rightMargin 0

#define bottomMargin 0

@interface ViewController ()

//web视图

@property(nonatomic,strong)UIWebView *webView;

@end


@implementation ViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    //加载HTML数据

    [self loadHTMLData];

}

-(void)setUpUI

{

    //创建web视图

    UIWebView *webVIew = [[UIWebView alloc] init];

    [self.view addSubview:webVIew];

    //约束

    [webVIew mas_makeConstraints:^(MASConstraintMaker *make) {

        make.top.offset(topMargin);

        make.left.offset(leftMargin);

        make.right.offset(rightMargin);

        make.bottom.offset(bottomMargin);

    }];

    //给属性赋值

    _webView = webVIew;

    

}

-(void)loadHTMLData

{

    //1.URL

    NSURL *url = [NSURL URLWithString:@"https://www.baidu.com"];

    //2.session单例

    NSURLSession *session = [NSURLSession sharedSession];

    //发起任务(dataTask):默认放在子线程中执行

    NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

        //data响应体,response响应头,error错误信息

        //错误处理

        if(error == nil && data != nil)

        {

            //NSLog(@"%@--%@--%@",data,response,[NSThread currentThread]);

            //添加到主队列刷新视图

            [[NSOperationQueue mainQueue] addOperationWithBlock:^{

                //反序列化HTML字符串

                NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

                //刷新视图

                [self setUpUI];

                [_webView loadHTMLString:html baseURL:url];

            }];

        }else

        {

            NSLog(@"%@",error);

        }

    }];

    //启动任务

    [dataTask resume];

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值