0

How can I check whether the app is connected to the internet or not? currently, I am using this code in my appdelegate.m file

dispatch_queue_t connectivityThread = dispatch_queue_create("com.gm.kart.connectivity", NULL);

dispatch_async(connectivityThread, ^{
    while (true){
        if([GMMConnectivity hasConnectivity])
            NSLog(@"%@", @"connected");
        else
            NSLog(@"Not connected");

        usleep(10000000);
    }
});

and when I click my login button I want to do a check whether the internet is connected or not using NSnotificationcenter?

Please help me

4

2 回答 2

11

下载下面的示例后。

http://developer.apple.com/iphone/library/samplecode/Reachability/index.html

您可以在您的项目中使用它,如下所示:-

included Apple's Reachability.h & .m from their Reachability example.

add the SystemConfiguration framework.

将波纹管方法放入您的 appdelegare.m 文件中:-

- (BOOL) connectedToNetwork{
    Reachability* reachability = [Reachability reachabilityWithHostName:@"google.com"];
    NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];

    if(remoteHostStatus == NotReachable)
    {
        isInternet =NO;
    }
    else if (remoteHostStatus == ReachableViaWWAN)
    {
        isInternet = TRUE;
    }
    else if (remoteHostStatus == ReachableViaWiFi)
    { isInternet = TRUE;

    }
    return isInternet;
}

isInternet 在您的 .h 类中是一个 BOOL declear

根据您的代码:-

dispatch_queue_t connectivityThread = dispatch_queue_create("com.GMM.assamkart.connectivity", NULL);

dispatch_async(connectivityThread, ^{
    while (true){
       isInternet =[self connectedToNetwork];
    if (isInternet)
    {
           NSLog(@"connected");
        }
        else
        {
            NSLog(@"Not connected");
        }
       // usleep(10000000);
    }
});
于 2013-04-17T10:01:01.667 回答
-1
-(BOOL) connectedToInternet

{
    NSString *URLString = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com"]];

return ( URLString != NULL ) ? YES : NO;

}
于 2013-10-07T11:07:09.587 回答