Reputation: 315
I have tried some of the posts available in this site. But in my iphone app if the internet is not connected it is not showing any error. it simply shows the loading view. i have used the following code for this
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
error=nil;
if(error != nil)
{
UIAlertView * alert;
if([[error localizedDescription] isEqualToString:@"no Internet connection"])
{
alert = [[UIAlertView alloc] initWithTitle:@"No Internet connection" message:[error localizedDescription] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
}
else
{
alert = [[UIAlertView alloc] initWithTitle:@"Connection failed" message:[error localizedDescription] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
}
[alert release];
}
}
This warning is never display even if the internet is not connected. Can anyone help me? Thanks in advance
Upvotes: 1
Views: 2158
Reputation: 1496
Use this code ...
define this
#define AF_INET 2
and implement this,
- (BOOL) connectedToNetwork
{
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;
}
use bool to check,
BOOL check = [self connectedToNetwork];
And then check this condition,
if (!check) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Warning!" message:@"Your internet connection is currently unavailable. Please try to connect later."
delegate:self cancelButtonTitle:@"Done" otherButtonTitles:nil];
[alert show];
[alert release];
}
Upvotes: 0
Reputation: 2163
Refer this Sample code from Apple regarding Reachability .
And implement certain necessary methods.
Upvotes: 4
Reputation: 8106
here are the error codes NSUrlConnection currently support
the error code for no internet connection is NSURLErrorNotConnectedToInternet = -1009,
you can use that in your condition when you got the NSError* error
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
if(error != nil)
{
if ([error code] == NSURLErrorNotConnectedToInternet) {
//not connected to internet
}
}
}
Upvotes: 0