3

I want to confirm that an URL is accessible/reachable before calling it. I knew reachabilityWithHostName method can help me to do this task. I used the following code to know about URL reachability. But it does not works.

Reachability *connection = [Reachability reachabilityWithHostName:@"stackoverflow.com"];

[connection startNotifier];

NetworkStatus netStatus = [connection currentReachabilityStatus];

The netStatus always returns NotReachable(means 0) value even everything is fine.

Notes:

  • I don't want to use any other third party reachability classes
  • I downloaded the current Reachability class from here
  • I placed the above lines of code in my sample project's viewDidLoad method
  • The last strange thing that I wonder is, If I set a breakpoint in the first line and run the code step by step by tapping step over button in Xcode, the netStatus returns correct value ?!?!?!?!

Help needed!! Confused!!

Community
  • 1
  • 1
Confused
  • 3,846
  • 7
  • 45
  • 72
  • Move code in didAppear and try prefix www your url. Try also with other address (if one site will throw out request time out every time due anti DDOS protections). – ares777 Mar 19 '15 at 09:57
  • yes, prefix http and try to add / at the end – Injectios Mar 19 '15 at 10:06
  • @user3344236 Already used www/http/https prefixes and tried other URL's too. Nothing works. Always throwing zero. – Confused Mar 19 '15 at 10:20
  • @Injectios http://stackoverflow.com/a/11284351/1389515 It seems we should not use http/https with host name – Confused Mar 19 '15 at 10:25
  • I DON'T remember exactly what should be done, but I remember I had the same issues, did you try to put slash at the end? – Injectios Mar 19 '15 at 10:32
  • Did you move code in DidAppear ? It seems for me the view or other controller is not fully loaded, then if you set breakpoints it is working due full load of view. – ares777 Mar 19 '15 at 10:39

1 Answers1

1

Use Reachability like here: https://github.com/tonymillion/Reachability

    Reachability *connection = [Reachability reachabilityWithHostName:@"stackoverflow.com"];
    connection.reachableBlock = ^(Reachability*reach)
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            NetworkStatus netStatus = [reach currentReachabilityStatus];
            NSLog(@"network status: %ld", netStatus);
        });
    };
    connection.unreachableBlock = ^(Reachability*reach)
    {
        NetworkStatus netStatus = [reach currentReachabilityStatus];
        NSLog(@"network status: %ld", netStatus);
    };

    [connection startNotifier];
iOSfleer
  • 408
  • 6
  • 20