How to verify network connectivity in objective-c

后端 未结 1 616
生来不讨喜
生来不讨喜 2021-02-01 11:20

I was looking over the Reachability sample project on developer.apple.com and found that it was a large project just to verify you had network connectivity.

First part o

相关标签:
1条回答
  • 2021-02-01 11:33

    It's not large, it really does what you want. If it is too big for you, you can extract what you need only like reachabilityForLocalWiFi. But I'm afraid that it will not be much smaller.

    Yes, you can use reachability in your application delegate or inside the first view controller.

    Reachability notification registration ...

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(networkReachabilityDidChange:)
                                                 name:kReachabilityChangedNotification
                                               object:nil];
    __reachability = [[Reachability reachabilityWithHostName:@"www.google.com"] retain];
    [__reachability startNotifier];
    

    ... callback method example ...

    - (void)networkReachabilityDidChange:(NSNotification *)notification {
      Reachability *reachability = ( Reachability * )[notification object];
      if ( reachability.currentReachabilityStatus != NotReachable ) {
        // Network is available, ie. www.google.com
      } else {
        // Network is not available, ie. www.google.com
      }
    }
    

    ... do not forget to stop notifications, remove observer and release rechability object.

    0 讨论(0)
提交回复
热议问题