2012-05-28 41 views
3

我已實施Reachability Api 2.2。當網絡從關閉狀態變爲開啓狀態時,它不會觸發。可達性類別在iOS中不起作用

此外,我可以在應用程序委託中實現它嗎?如果是這樣,我應該在哪裏刪除觀察者?

這裏是我的代碼(這不叫開除模型的viewController)

- (void)viewDidLoad 
{ 
    // check for internet connection 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkNetworkStatus:) name:kReachabilityChangedNotification object:nil]; 

    internetReachable = [[Reachability reachabilityForInternetConnection] retain] ; 
    [internetReachable startNotifier]; 
    // check if a pathway to a random host exists 
    hostReachable = [[Reachability reachabilityWithHostName: @"www.google.com"] retain]; 
    [hostReachable startNotifier]; 
} 

- (void) checkNetworkStatus:(NSNotification *)notice 
{ 
    // called after network status changes 

    NetworkStatus hoststatus=[hostReachable currentReachabilityStatus]; 

    NetworkStatus internetStatus=[internetReachable currentReachabilityStatus]; 

    for (NSString *msg in messageArray) { 
     [stringg appendString:[NSString stringWithFormat:@"%@",msg]]; 
    } 

    if (hoststatus==NotReachable||internetStatus==NotReachable) { 
     [self.navigationController presentModalViewController:inter animated:YES]; 
    } 
    else{ 
     [self dismissModalViewControllerAnimated:YES]; 
    } 

    [inter release]; 
} 



- (void)viewDidUnload 
{ 

    [[NSNotificationCenter defaultCenter] removeObserver:self]; 
    [super viewDidUnload]; 
} 
+0

你正在泄漏'internetReachable';有一個'保留'沒有配對'釋放'/'autorelease' –

回答

1

你在哪裏註冊的通知?

你需要的東西是這樣的:

[[NSNotificationCenter defaultCenter] addObserver:self 
             selector:@selector(reachabilityChange:) 
              name:kReachabilityChangedNotification 
              object:nil]; 

我用的是這樣一個參數傳遞的可達性對象:

- (void) reachabilityChange: (NSNotification*) notification 
{ 
    Reachability* curReach = [notification object]; 
    NSParameterAssert([curReach isKindOfClass: [Reachability class]]); 
    BOOL isServerCurrentlyReachable = (NotReachable != [curReach currentReachabilityStatus]); 
    BOOL wasServerPreviouslyReachable = self.isServerReachable; 
    self.isServerReachable = isServerCurrentlyReachable; 

    if (NO == wasServerPreviouslyReachable && YES == isServerCurrentlyReachable) 
    { 
     // Moving from non reachable to reachable state 

    } 
    else if (YES == wasServerPreviouslyReachable && NO == isServerCurrentlyReachable) 
    { 
     // Moving from a reachable to a non reachable state 

    } 
} 

你似乎沒有被使用。

此外,通知可能會以相同的狀態被多次調用,因此您需要確保將這一點考慮在內,就像在代碼片段中所做的那樣。

如果您在應用程序委託中使用它,停止/刪除applicationDidResignActive中的內容似乎是適當的地方。

+0

耶我補充說,但仍然。其實如果我重新啓動我的調制解調器,然後它檢測到網絡關閉但是當網絡繼續時,它不會檢測到這一點。雖然如果我從mac關閉wifi,然後它會檢測開啓和關閉 – Mann

+0

您沒有使用作爲參數傳遞的可達性實例 – Gruntcakes

0

包括從開發蘋果的project.Import SystemConfiguration框架從SDK庫Reachability.h和Reachability.m文件到您的project.Then以下GlobalFunction.h和GlobalFunction.m文件添加到您的項目

//GlobalFunction.h 


#import <Foundation/Foundation.h> 

@class Reachability; 

@interface GlobalFunction : NSObject 
{ 
Boolean internetActive; 
Boolean hostActive; 

Reachability * internetReachable; 
Reachability * hostReachable; 
Reachability * wifiReach; 

} 

@property (readwrite,assign) Boolean internetActive; 
@property (readwrite,assign) Boolean hostActive; 

- (Boolean) checkNetworkStatus; 
- (BOOL)connectedToNetwork; 
@end 


//GlobalFunction.m 

#import "GlobalFunction.h" 
#import "Reachability.h" 
#include <netinet/in.h> 
#import <SystemConfiguration/SCNetworkReachability.h> 

@implementation GlobalFunction 

    @synthesize internetActive,hostActive; 
    - (id)init 
    { 
self = [super init]; 
    if (self) { 
// Initialization code here. 
    } 

return self; 
} 



// Checking Internet Connectivity 
- (Boolean) checkNetworkStatus//:(NSNotification *)notice 
    { 
// called after network status changes 
    internetReachable = [[Reachability reachabilityForInternetConnection] retain]; 
    [internetReachable startNotifier]; 

    // check if a pathway to a random host exists 
    hostReachable = [[Reachability reachabilityWithHostName: @"www.apple.com"] retain]; 
    [hostReachable startNotifier]; 

    NetworkStatus internetStatus = [internetReachable currentReachabilityStatus]; 
    switch (internetStatus) 
{ 
case NotReachable: 
{ 
    //NSLog(@"The internet is down."); 
    //[self ShowMsg:@"The internet connection appears to be offline."]; 
    self.internetActive = NO; 
    break; 

} 
case ReachableViaWiFi: 
{ 
    //NSLog(@"The internet is working via WIFI."); 
    self.internetActive = YES; 

    break; 

} 
case ReachableViaWWAN: 
{ 
    //NSLog(@"The internet is working via WWAN."); 
    self.internetActive = YES; 

    break; 

} 
default : 
    self.internetActive = YES; 
    break; 

} 

NetworkStatus hostStatus = [hostReachable currentReachabilityStatus]; 
switch (hostStatus) 

    { 
case NotReachable: 
{ 
    //NSLog(@"A gateway to the host server is down."); 
    self.hostActive = NO; 

    break; 

} 
case ReachableViaWiFi: 
{ 
    //NSLog(@"A gateway to the host server is working via WIFI."); 
    self.hostActive = YES; 

    break; 

} 
case ReachableViaWWAN: 
{ 
    //NSLog(@"A gateway to the host server is working via WWAN."); 
    self.hostActive = YES; 

    break; 

    } 
} 

    [hostReachable release]; 
    [internetReachable release]; 

return self.internetActive; 
    } 



    - (BOOL)connectedToNetwork 
{ 
    // Create zero addy 
    struct sockaddr_in zeroAddress; 
bzero(&zeroAddress, sizeof(zeroAddress)); 
zeroAddress.sin_len = sizeof(zeroAddress); 
zeroAddress.sin_family = AF_INET; 
// Recover reachability flags 
    SCNetworkReachabilityRef defaultRouteReachability =                   SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr*)&zeroAddress); 
SCNetworkReachabilityFlags flags; 
BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags); 
CFRelease(defaultRouteReachability); 
    if (!didRetrieveFlags) 
    { 
//NSLog(@"Error. Could not recover network reachability flags"); 
return 0; 
    } 
    BOOL isReachable = flags & kSCNetworkFlagsReachable; 
    BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired; 
    //below suggested by Ariel 
    BOOL nonWiFi = flags & kSCNetworkReachabilityFlagsTransientConnection; 
    NSURL *testURL = [NSURL URLWithString:@"http://www.apple.com/"]; 
    //comment by friendlydeveloper: maybe use www.google.com 
    NSURLRequest *testRequest = [NSURLRequest requestWithURL:testURL    cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:20.0]; 
    //NSURLConnection *testConnection = [[NSURLConnection alloc]  initWithRequest:testRequest delegate:nil]; //suggested by Ariel 
    NSURLConnection *testConnection = [[[NSURLConnection alloc] initWithRequest:testRequest delegate:nil] autorelease]; 
//modified by friendlydeveloper 
    return ((isReachable && !needsConnection) || nonWiFi) ? (testConnection ? YES : NO) : NO; 

    } 

-(void)dealloc 
{ 
internetReachable=nil; 
hostReachable=nil; 
wifiReach=nil; 

[super dealloc]; 
} 

@end 




    ------>Just write the code for checking internet connection 
#import<GlobalFunction.m> 

-(void)viewDidLoad 
    { 
    if([globalFunc checkNetworkStatus]) 
{ 
[self ShowAlert:@"Internet Connection appears"]; 
    } 
else 
{ 
[self ShowAlert:@"The Internet connection appears to be offline.."]; 
} 
}