How to check if the connection is available ( iphone )?
I used the following code to check this---
(the request is my request)NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if( theConnection )
{
nslog(@"connection is present");
}
else
{-------error message1-------------
}
and then in the delegates I relay on to receive response
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
-------error message2-------------
}
I am presently checking everything on my simulator...and...detecting internet connection by just removing my internet cable...
but every time my program I got only message 2.....but it comes after 1 min(conne开发者_如何学Cction time over)...
but I want to check it in as minimum time as possible....
Use this method:
- (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;
}
You may want to take a look at the Reachability exaxmple provided by Apple.
If you want your NSURLConnection to fail earlier, you need to specify a timeout in your NSURLRequest: requestWithURL:cachePolicy:timeoutInterval:
精彩评论