IOS 利用Reachability检查网络状态

2011-06-15

这里使用的是 Reachability2.0 呵呵 一些代码来自网上,现在自己的blog上只是为了以后方便记忆。呵呵 代码的具体实现:

MyAppDelegate.h

#import 
#import "Reachability.h"

@interface MyAppDelegate : NSObject  {
    UIWindow *window;
    UIAlertView * alter;
    Reachability *hostReach;
}

@property (nonatomic, retain) UIWindow *window;

-(void)reachabilityChanged:(NSNotification *)note;
-(void)updateInterfaceWithReachability:(Reachability *)curReach;
@end

MyAppDelegate.m

#import "ColdplayAppDelegate.h"

@implementation MyAppDelegate

@synthesize window;

-(void)reachabilityChanged:(NSNotification *)note
{
    Reachability * curReach = [note object];
    NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
//    NetworkStatus status = [curReach currentReachabilityStatus];
    [self updateInterfaceWithReachability:curReach];
}

-(void)updateInterfaceWithReachability:(Reachability *)curReach
{
    NetworkStatus status = [curReach currentReachabilityStatus];
    if (status == NotReachable)
    {
        alter = [[UIAlertView alloc] initWithTitle:@"guoku" 
                                            message:@"一个坏消息:你的网络有问题哦。一个好消息:你的可以重试下。:)" 
                                            delegate:nil 
                                            cancelButtonTitle:nil 
                                            otherButtonTitles:nil, nil];
        [NSTimer scheduledTimerWithTimeInterval:5.0f target:self selector:@selector(performDismiss:) userInfo:nil repeats:NO];
        [alter show];
//        [alter release];
    }
}

-(void) performDismiss:(NSTimer *)timer
{
    [alter dismissWithClickedButtonIndex:0 animated:NO];
//    [alter release];
}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
    if (!window) 
    {
        [self release];
        return NO;
    }
     
    [[NSNotificationCenter defaultCenter] 
           addObserver:self selector:@selector(reachabilityChanged:) 
           name:kReachabilityChangedNotification 
           object:nil];
    hostReach = [[Reachability reachabilityWithHostName:@"www.apple.com.cn"] retain];
    [hostReach startNotifier];
    
    [self.window makeKeyAndVisible];
    [window layoutSubviews];
    return YES;
}


- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [alter release];
    [hostReach release];
    [window release];
    [super dealloc];
}

@end