iOS / iPhone SDK:网络失去连接/恢复时是否有事件?

3

我希望在失去连接和重新连接时进行一些处理。是否有事件来处理它?

提前感谢,

E.


你可以参考 https://dev59.com/t1LTa4cB1Zd3GeqPd9Qm 来获取帮助。 - Ravi
2个回答

0

你应该使用 ASIHTTPRequest 中使用的良好实践。 它们使用 Reachability,据他们所说,这是由 Apple开发的类的替代品。 我希望这会有所帮助。


0

一个标准的方法是使用Reachability来测试网络可用性。可以在这里下载。您只需要在项目中添加Reachability.h和Reachability.m文件。

我个人的偏好是按照以下步骤进行 -

1 添加Reachability文件

2 为您希望在项目中记住/公开的每个网络测试创建BOOL属性 - 我下面有一个针对Google和一个针对Google Maps的测试。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接