iOS中判斷網絡是否聯網


#import "AppDelegate.h"

#import "ViewController.h"
#import "Reachability.h"


@interface AppDelegate (){
}
@property (nonatomic,retain)Reachability *res;

@end

@implementation AppDelegate

- (void)dealloc
{
    [_window release];
    [_res release];
    [_viewController release];
    [super dealloc];
}

-(void)change:(NSNotificationCenter *)notify{//當網絡發生變化的時候,都會觸發這個事件
    NSLog(@"%@",notify);
}

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

//添加網絡變化的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(change:) name:kReachabilityChangedNotification object:nil];
    self.res=[Reachability reachabilityWithHostName:@"http://www.baidu.com"];
    [self.res startNotifier];//開始監聽網絡請求的變化
    
    
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    // Override point for customization after application launch.
    self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease];
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];
    return YES;
}
、-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if([Reachability reachabilityForLocalWiFi].currentReachabilityStatus==NotReachable&&[[Reachability reachabilityForInternetConnection] currentReachabilityStatus]==NotReachable){
        NSLog(@" not  work");
    }
 
}

-(void)PdNetwork{
    Reachability *r=[Reachability reachabilityWithHostName:@"http://www.baidu.com"];
    switch ([r currentReachabilityStatus]) {
        case NotReachable:
            NSLog(@"not work");
            break;
        case ReachableViaWiFi:
            NSLog(@"wifi");
            break;
        case ReachableViaWWAN:{
            NSLog(@"wan");
        }
            break;
        default:
            break;
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM