这需要检测网络状态,只需要有网和没网两种状态即可(处理多种状态时可以在下边的通知方法netChanged中添加)。这里用到的是第三方框架Reachability
地址是这里
在viewController的viewDidLoad中添加监控网络的方法
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor lightGrayColor];
[self monitorNetworkState];
}
/** 监控网络状态 */
-(void)monitorNetworkState{
//kReachabilityChangedNotification是Reachability中的通知名称
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(netChanged:) name:kReachabilityChangedNotification object:nil];
Reachability *net = [Reachability reachabilityForInternetConnection];
[net startNotifier];
}
-(void)netChanged:(NSNotification *)notification{
Reachability *reachability = (Reachability *)notification.object;
NetworkStatus status = reachability.currentReachabilityStatus;
if (status != NotReachable) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"有网了" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
[alert show];
}
}
上边的代码即可满足需求