学习iOS编写程序时经常会判断没网络时候会崩溃的问题.
//初始化数据
- (void)_loadData
{
//发网络请求
[WXDataService requestAFWithURL:@"填写请求网址" params:nil requestHeader:nil httpMethod:@"GET或者填写POST" block:^(NSObject *result) {
//判断没网的时候会崩溃
if ([result isKindOfClass:[NSError class]]) {
return [self internetFail];//可以调用一个方法,显示没网络的时候显示的画面.
}
NSLog(@"result:%@",result);
//创建可变数组存放models
NSMutableArray *models=[[NSMutableArray alloc]init];
NSDictionary *results = (NSDictionary *)result;
NSArray *datas = results[@"datas"];
for (NSDictionary *dic in datas) {
NSArray *infos = dic[@"infos"];
for (NSDictionary *subDic in infos) {
NSLog(@"infos=%@",infos);
TicketModel *model=[[TicketModel alloc]initWithContentsOfDic:subDic];
[models addObject:model];
}
self.dataList = models;
[_tableView reloadData];//重新加载 刷新表视图.
}
}];
}
/*
没网络时提示
如加载这样一个画面
*/
//网络加载失败弹出的界面调用
- (void)internetFail
{
UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(150, 100, 80, 80)];
imageView.image=[UIImage imageNamed:@"detailHotelIconSet@2x"];
[self.view addSubview:imageView];
UILabel *label=[[UILabel alloc]init];
label.frame=CGRectMake(130,200,kScreenWidth-100, 50);
label.text=@"亲,信息为加载失败";
label.font=[UIFont boldSystemFontOfSize:14];
[self.view addSubview:label];
UILabel *label1=[[UILabel alloc]init];
label1.frame=CGRectMake(80,250, kScreenWidth-100, 50);
label1.text=@"请检查你的手机网络设置,点击重新加载";
label1.font=[UIFont boldSystemFontOfSize:14];
label1.numberOfLines=0;
[self.view addSubview:label1];
}
原文地址:http://blog.csdn.net/xiangrikui524/article/details/45192703