#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];
}