2012-01-13 55 views

回答

0

一個標準方法是使用可達測試網絡的可用性。它可以下載here。您只需在項目中使用Reachability.h和Reachability.m。

我個人的偏好是做到以下幾點 -

1添加的可達性文件

2您要記住/揭露項目中的每個網絡測試創建BOOL性能 - 我有一個谷歌測試並在下面的谷歌地圖測試。

3在你的appDidFinishLoading方法中調用[self assertainNetworkReachability]。

#pragma mark - 
#pragma mark Reachability 

-(void)assertainNetworkReachability { 
    [self performSelectorInBackground:@selector(backgroundReachabilityTests) withObject:nil]; 
} 

-(void)backgroundReachabilityTests { 

    self.isInternetReachable = [self internetReachable]; 
    self.isMapsReachable = [self mapsReachable]; 

    self.connectivityTimer = [NSTimer scheduledTimerWithTimeInterval:60.0 target:self  selector:@selector(backgroundReachabilityTests) userInfo:nil repeats:NO]; 
} 

-(BOOL)hostReachable:(NSString*)host { 
    Reachability *r = [Reachability reachabilityWithHostName:host]; 
    NetworkStatus internetStatus = [r currentReachabilityStatus]; 
    if(internetStatus == NotReachable) { 
     [self throwNetworkDiagnosisAlert]; 
     return NO; 
    } 
    return YES; 
} 

-(BOOL)internetReachable { 
    return [self hostReachable:@"www.google.co.uk"]; 
} 

-(BOOL)mapsReachable { 
    return [self hostReachable:@"maps.google.com"]; 
} 

-(BOOL)isInternetGoodYetMapsUnreachable { 
    return (self.isInternetReachable && !self.isMapsReachable); 
} 

-(void)throwNetworkDiagnosisAlert { 
    NSString* title = @"Connectivity Problem"; 
    NSString* message = @"You are not connected to the internet."; 

    if (self.isInternetGoodYetMapsUnreachable) { 
     message = @"Unable to connect to the Google Maps server."; 
    } 

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil]; 
    [alert show]; 
    [alert release]; 
}