0

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(connection time over)...

but I want to check it in as minimum time as possible....

Jack
  • 10,783
  • 12
  • 46
  • 65
Ranjeet Sajwan
  • 1,888
  • 2
  • 28
  • 60
  • possible duplicate of [How to check for an active Internet Connection on iPhone SDK?](http://stackoverflow.com/questions/1083701/how-to-check-for-an-active-internet-connection-on-iphone-sdk) – Jesse Beder Nov 01 '10 at 07:07

2 Answers2

3

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;
}
Jesse Beder
  • 30,017
  • 18
  • 97
  • 140
arunkumar.p
  • 1,745
  • 4
  • 18
  • 30
2

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:

Joseph Tura
  • 6,046
  • 6
  • 41
  • 70
  • no i don't want to my NSURLConnection to fail earlier...this will create problem in those cases where internet connection is slow.. i want just to check if internet connection is available...if yes only then the request should send... – Ranjeet Sajwan Nov 01 '10 at 07:18
  • Check out the Reachability example, then. You could create a proxy that keeps track of changes in reachability. That way you will always know whether a connection exists. You can then adapt your interface accordingly (e.g. disable buttons, show action sheets etc., if no connectivity exists). – Joseph Tura Nov 01 '10 at 07:22