网络监听主要是基于ASIHTTPRequest内的Reachability的调用

可以在AppDelegate内写,也可以自己定义单例来写这个操作。

 1 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
 2 {
 3     // Override point for customization after application launch.
 4     
 5     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
 6     self.hostReach = [Reachability reachabilityWithHostName:@"www.apple.com"] ;
 7     [self.hostReach startNotifier]; //开始监听,会启动一个run loop
 8     
 9    
10     return YES;
11 }
 1 /**
 2  *  网络链接改变时会调用的方法
 3  */
 4 -(void)reachabilityChanged:(NSNotification *)note {
 5     Reachability *currReach = [note object];
 6     NSParameterAssert([currReach isKindOfClass:[Reachability class]]);
 7     //对连接改变做出响应处理动作
 8     NetworkStatus status = [currReach currentReachabilityStatus];
 9     //如果没有连接到网络就弹出提醒实况
10     self.isReachable = YES;
11     if(status == NotReachable) {
12         UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络连接异常" message:@"请检测网络连接" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
13         [alert show];
14         self.isReachable = NO;
15     }
16     else {
17         UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络连接信息" message:@"网络连接正常" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
18         [alert show];
19         self.isReachable = YES; 
20     }
21 }
 1 //调用方法
 2 AppDelegate *appDlg = (AppDelegate *)[[UIApplication sharedApplication] delegate];  
 3 if(appDlg.isReachable)  
 4 {  
 5     NSLog(@"网络已连接");//执行网络正常时的代码   
 6 }  
 7 else  
 8 {  
 9     NSLog(@"网络连接异常");//执行网络异常时的代码   
10 } 

不用于appdelegate里面的方法:

#import

@interface CheckNetwork : NSObject {
   
}
+(BOOL)isExistenceNetwork;
@end
#import "CheckNetwork.h"
#import "Reachability.h"
@implementation CheckNetwork
+(BOOL)isExistenceNetwork
{
    BOOL isExistenceNetwork = FALSE;
    Reachability *r = [Reachability reachabilityWithHostName:@"www.apple.com"];
    switch ([r currentReachabilityStatus]) {
        case NotReachable:
            isExistenceNetwork=FALSE;
         //   NSLog(@"没有网络");
            break;
        case ReachableViaWWAN:
            isExistenceNetwork=TRUE;
         //   NSLog(@"正在使用3G网络");
            break;
        case ReachableViaWiFi:
            isExistenceNetwork=TRUE;
          //  NSLog(@"正在使用wifi网络");       
            break;
    }
//    if (!isExistenceNetwork) {
//        UIAlertView *myalert = [[UIAlertView alloc] initWithTitle:@"警告" message:@"网络不存在" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil,nil];
//        [myalert show];
//        [myalert release];
//    }
    return isExistenceNetwork;
}
@end
原文地址:https://www.cnblogs.com/ubersexual/p/3429042.html