Search code examples
iosobjective-creachabilityconnectivity

How to check whether internet is active (checking both network availability & webpage accessibility) in iOS?


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?


Solution

  • 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");
            }