如何检查连接是否可用(iphone)?

时间:2010-11-01 06:06:03

标签: iphone objective-c

我使用以下代码来检查---
(请求是我的要求)

NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

if( theConnection )
{
    nslog(@"connection is present");

}
else
{-------error   message1-------------
}

然后在代表中继续接收回复

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
-------error   message2-------------
}

我目前正在检查模拟器上的所有内容......并且......只需移除我的网线即可检测互联网连接......

但是每次我的节目我只收到消息2 .....但是1分钟后(连接时间结束)...

但我希望尽可能在最短时间内检查....

2 个答案:

答案 0 :(得分:3)

使用此方法:

- (BOOL) connectedToNetwork
{
 // Create zero addy
 struct sockaddr_in zeroAddress;
 bzero(&zeroAddress, sizeof(zeroAddress));
 zeroAddress.sin_len = sizeof(zeroAddress);
 zeroAddress.sin_family = AF_INET;

 // Recover reachability flags
 SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
 SCNetworkReachabilityFlags flags;

 BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
 CFRelease(defaultRouteReachability);

 if (!didRetrieveFlags)
 {
     printf("Error. Could not recover network reachability flags\n");
     return 0;
 }

 BOOL isReachable = flags & kSCNetworkFlagsReachable;
 BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
 return (isReachable && !needsConnection) ? YES : NO;
}

答案 1 :(得分:2)

您可能需要查看Apple提供的Reachability exaxmple

如果您希望NSURLConnection先前失败,则需要在NSURLRequest中指定超时:requestWithURL:cachePolicy:timeoutInterval: