iOS / iPhone SDK:是否存在网络丢失/返回的事件?

时间:2012-01-13 09:09:04

标签: ios events networking sdk

当我断开连接时,以及连接恢复时,我想做一些处理。 是否有任何事件可以处理它?<​​/ p>

先谢谢,

电子。

2 个答案:

答案 0 :(得分:0)

您应该使用ASIHTTPRequest中使用的良好做法。 他们使用Reachability就像他们所说的那样,通过Apple来取代班级。 我希望它会有所帮助

答案 1 :(得分:0)

一种标准方法是使用可达性来测试网络可用性。它可以下载here。您只需在项目中使用Reachability.h和Reachability.m。

我个人的偏好是执行以下操作 -

1添加Reachability文件

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];
}