众所周知,我们在开发APP时,涉及网络连接的时候,都会想着提前判断一下当前的网络连接状态,如果没有网络,就不再请求url,省去不必要的步骤,所以,这个如何判断?其实很简单。
前提:工程添加:SystemConfiguration.framework framework
然后在需要判断的类中包含头文件:
#import "Reachability.h"
【如果你使用的ASIHTTPRequest类库,那么直接import Reachbility.h就可以了,ASIHTTP类库里包含Reachbility.h和.m】
下面是我写的一个方法:
-(BOOL) isConnectionAvailable{ BOOL isExistenceNetwork = YES; Reachability *reach = [Reachability reachabilityWithHostName:@""]; switch ([reach currentReachabilityStatus]) { case NotReachable: isExistenceNetwork = NO; //NSLog(@"notReachable"); break; case ReachableViaWiFi: isExistenceNetwork = YES; //NSLog(@"WIFI"); break; case ReachableViaWWAN: isExistenceNetwork = YES; //NSLog(@"3G"); break; } if (!isExistenceNetwork) { MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];//MBProgressHUD为第三方库,不需要可以省略或使用AlertView hud.removeFromSuperViewOnHide =YES; hud.mode = MBProgressHUDModeText; hud.labelText = NSLocalizedString(INFO_NetNoReachable, nil); hud.minSize = CGSizeMake(132.f, 108.0f); [hud hide:YES afterDelay:3]; return NO; } return isExistenceNetwork; }
所以举一反三,如果你不单单是判断是否网络通畅,而是要判断是WIFI或3G,再写一个isEnableWIFI的方法,具体判断方法就不用再赘述了吧,currentReachabilityStatus判断之。
是不是很方便?项目更合理了呢?
130529