如何解决iPhone中的互联网检查问题?

时间:2011-07-10 18:16:55

标签: iphone alert reachability internet-connection

我正在开发一个应用程序,我必须检查互联网连接。我使用两个文件Reachability.h和Reachability.m。现在我必须在互联网不工作时显示警报。

但是当我的观察者检查互联网时,它会显示一次以上的警报视图。有时它会显示9-10次警报。 我的代码在这里:

<。>文件中的

Reachability* internetReachable;
    Reachability* hostReachable;
    NetworkStatus internetStatus;
<。>文件中的

        internetReachable = [[Reachability reachabilityForInternetConnection] retain];
        [internetReachable startNotifier];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkNetworkStatus:) name:kReachabilityChangedNotification object:nil];
        hostReachable = [[Reachability reachabilityWithHostName: @"www.apple.com"] retain];
        [hostReachable startNotifier];



- (void) checkNetworkStatus:(NSNotification *)notice    
     {
        internetStatus = [internetReachable currentReachabilityStatus];

        if (internetStatus != NotReachable){
            NSLog(@"internet is on");

        }
        else {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error!" message:@"Server not connected or down!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alert show];
            [alert release];
            internetCount++;
        }           
}

此代码在委托中,同样我在其他类中使用此代码,我必须检查互联网

plz help

1 个答案:

答案 0 :(得分:2)

我没有使用Reachability,因为我遇到了像你这样的问题,所以我创建了自己的实现。只需导入下面的头文件,然后拨打[self networkIsReachable]以检查互联网连接。

    #import <netinet/in.h>
    - (BOOL)networkIsReachable 
    {
        struct sockaddr_in zeroAddress;
        bzero(&zeroAddress, sizeof(zeroAddress));
        zeroAddress.sin_len = sizeof(zeroAddress);
        zeroAddress.sin_family = AF_INET;

        SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
        SCNetworkReachabilityFlags flags;
        BOOL gotFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
        CFRelease(defaultRouteReachability);
        if (!gotFlags) {
            return NO;
        }
        BOOL isReachable = flags & kSCNetworkReachabilityFlagsReachable;

        BOOL noConnectionRequired = !(flags & kSCNetworkReachabilityFlagsConnectionRequired);
        if ((flags & kSCNetworkReachabilityFlagsIsWWAN)) {
            noConnectionRequired = YES;
        }

        return (isReachable && noConnectionRequired) ? YES : NO;
    }