在NSURLRequest下面调用UIWebView后,测试会奔溃

qq_14873045 2017-05-01 10:08:29
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.

// 1.创建url
// 请求一个网页
NSString *urlString = @"http://www.xinsandai.com/api/get_JsonNewsInfo.php?pid=2084";
// 一些特殊字符编码
urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSURL *url = [NSURL URLWithString:urlString];
// 2.创建请求 并:设置缓存策略为每次都从网络加载 超时时间30秒
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30];
// 3.采用苹果提供的共享session
NSURLSession *sharedSession = [NSURLSession sharedSession];
// 4.由系统直接返回一个dataTask任务
NSURLSessionDataTask *dataTask = [sharedSession dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
// 网络请求完成之后就会执行,NSURLSession自动实现多线程
NSDictionary*dicRoot = [NSJSONSerialization JSONObjectWithData: data options:NSJSONReadingMutableContainers error:nil];
if (data && (error == nil)) {
// 网络访问成功
//NSLog(@"data=%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
NewsInfoModel*model = [[NewsInfoModel alloc] init];
model.mTitle = [dicRoot objectForKey:@"title"];
model.mBody = [dicRoot objectForKey:@"body"];
model.mID = [dicRoot objectForKey:@"aid"];
//NSLog(@"%@",model.mBody);
UILabel*title = [[UILabel alloc] initWithFrame:CGRectMake(10, 60, self.view.bounds.size.width-20, 40)];
title.text = model.mTitle;
title.numberOfLines = 2;
title.font = [UIFont systemFontOfSize:14];
[self.view addSubview:title];
CGRect bouds = [[UIScreen mainScreen] applicationFrame];
_webView = [[UIWebView alloc] initWithFrame:bouds];
_webView.scalesPageToFit = YES;
_webView.delegate = self;
[_webView loadHTMLString:@"<p>Hello</p>" baseURL:nil];
[self.view addSubview:_webView];

} else {
// 网络访问失败
NSLog(@"error=%@",error);
}
}];

// 5.每一个任务默认都是挂起的,需要调用 resume 方法
[dataTask resume];

}

测试程序会奔溃,单独调用UIWebView没问题
希望大大们指教
...全文
307 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq_14873045 2017-05-02
  • 打赏
  • 举报
回复
引用 1 楼 scribbler 的回复:
在下面代码中,判断data是否为nil? NSDictionary*dicRoot = [NSJSONSerialization JSONObjectWithData: data options:NSJSONReadingMutableContainers error:nil];
不是啊, if (data && (error == nil)) { 判断data不为空并且error不为空执行
scribbler 2017-05-02
  • 打赏
  • 举报
回复
在下面代码中,判断data是否为nil? NSDictionary*dicRoot = [NSJSONSerialization JSONObjectWithData: data options:NSJSONReadingMutableContainers error:nil];

29,030

社区成员

发帖
与我相关
我的任务
社区描述
主要讨论与iOS相关的软件和技术
社区管理员
  • iOS
  • 大熊猫侯佩
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧