检测网络状态的方法

来源:互联网 发布:外文数据库下载 编辑:程序博客网 时间:2024/04/30 06:22

#import<UIKit/UIKit.h>

#import"Reachability.h" (需要到导入第三Reachability库)


@classViewController;

@classAppDelegate;


@protocol AppDelegateDelegate <NSObject>


- (void)update:(AppDelegate*)appDelegate;


@end


@interface AppDelegate :UIResponder <UIApplicationDelegate>


@property (strong,nonatomic) UIWindow *window;

@property (assign,nonatomic) NetworkStatus netstatus;

@property (assign,nonatomic) BOOL isConnected;

@property (retain,nonatomic) Reachability *hostReach;

@property (assign,nonatomic) id<AppDelegateDelegate>delegate;


@end


#import"AppDelegate.h"

#import"ViewController.h"


@implementation AppDelegate


- (void)dealloc

{

    [_windowrelease];

    [_hostReachrelease];

    [superdealloc];

}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

    

   _isConnected = NO;

    [[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(ReachabilityChanged:)name:kReachabilityChangedNotificationobject:nil];

    

   self.hostReach = [ReachabilityreachabilityWithHostName:@"www.baidu.com"];

    [_hostReachstartNotifier];


    

   self.window = [[[UIWindowalloc] initWithFrame:[[UIScreenmainScreen] bounds]]autorelease];

   // Override point for customization after application launch.

  ViewController *viewController = [[ViewControlleralloc] init];

    

   UINavigationController *navigationController = [[UINavigationControlleralloc]initWithRootViewController:viewController];

    [viewController release];

    self.window.rootViewController = navigationController;

    [navigationControllerrelease];

    [self.windowmakeKeyAndVisible];

      

   return YES;

}


//网络监听事件

- (void)ReachabilityChanged:(NSNotification*)notice

{


    NSString *connectionKind = nil;

    Reachability *curReach = [notice object];

   NSParameterAssert([curReachisKindOfClass:[Reachabilityclass]]);

   _netstatus = [curReach currentReachabilityStatus];

    

   switch (_netstatus) {

       case NotReachable:

            connectionKind =@"当前没有网络连接\n请查看你的网络设置";

            _isConnected = NO;

            break;

       case ReachableViaWiFi:

            connectionKind =@"当前使用的网络是WIFi";

            _isConnected = YES;

            break;

       case ReachableViaWWAN:

            connectionKind =@"当前使用的网络是WWAN";

            _isConnected = YES  ;

            break;

        default:

            break;

    }

    

   UIAlertView *alert = [[UIAlertViewalloc]initWithTitle:@"提醒"message:connectionKind delegate:selfcancelButtonTitle:@"OK"otherButtonTitles: nil];

    [alert show];

    [alert release];

    

   if (_delegate && [_delegaterespondsToSelector:@selector(update:)]) {

        

        [_delegateperformSelector:@selector(update:)withObject:self];

        

    }


}



@end



原创粉丝点击