2
votes

I am currently working in an iOS project where I need to check whether my phone is connected to the internet (mobile data/wifi) or not. I'm using reachability class which only check network connection availability but suppose a scenario where there is no balance in my phone. In that case I wouldn't able to access internet but still reachability shows me that internet is reachable via mobile network as data connection is on although I can't access the page.

How can I resolve the issue?

3
I'm sick of this topic. Run a search, silly. - El Tomato
check out my answer - Md. Ibrahim Hassan

3 Answers

3
votes

you can check using connection:didReceiveResponse:

        NSString *urlString=@"yourUrl";
        NSURL *url=[NSURL URLWithString:urlString];
        NSURLRequest *request=[NSURLRequest requestWithURL:url];
        NSURLConnection *connection=[NSURLConnection connectionWithRequest:request delegate:self];
        [connection start];

        -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
        {
        NSLog(@"%@",response);
        [connection cancel];
        NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
        int code = (int)[httpResponse statusCode];
        if (code == 200) {
            NSLog(@"File exists");
        }
        else if(code == 404)
        {
            NSLog(@"File not exist");
        }
        }
        -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
        {
        NSLog(@"File not exist");
        }
1
votes

Another example would be if you're improperly connected to a Wifi network - your phone has a good connection but no permission to access any pages on the Internet.

In this case, the only method of detection would be to try and send a web request to a reliable site (say www.google.com). If your request to this source times out after a set amount of time (say five seconds) then you can safely conclude that the phone has connectivity issues.

0
votes

You can check the internet connection

NSURL *scriptUrl = [NSURL URLWithString:@"http://www.google.com/"];

NSData *data = [NSData dataWithContentsOfURL:scriptUrl];
//Manual timeout of 20 seconds
[NSThread sleepForTimeInterval: 20];
if (data)
    NSLog(@"Device is connected to the Internet");
else
    NSLog(@"Device is not connected to the Internet");

Refer to this link