iOS: Reachability - startNotifier fails after returning to app

大兔子大兔子 提交于 2019-12-05 13:06:42

You should only need to call [self.hostReachability startNotifier] once on init/load. Here's a rundown of your basic needs, using notifications rather than the block method on the linked thread:

  1. Add the tonymillion/Reachability library to your project.

  2. Create property for your Reachability object to make sure it's retained, eg.

    @interface ViewController () {
      NSString *_HOST;
    }
    @property Reachability *hostReachability;
    @end
    
  3. Register for change notifications, and start the notifier, eg.

    - (void)viewDidLoad
    {
      [super viewDidLoad];
    
      [[NSNotificationCenter defaultCenter] addObserver:self
                                               selector:@selector(reachabilityChanged:)
                                                   name:kReachabilityChangedNotification
                                                 object:nil];
    
      _HOST = @"www.google.com";
      self.hostReachability = [Reachability reachabilityWithHostname:_HOST];
      [self.hostReachability startNotifier];
    }
    
    - (void)viewDidUnload
    {
      [super viewDidUnload];
    
      [[NSNotificationCenter defaultCenter] removeObserver:self];
    }
    
  4. Finally, create a reachabilityChanged: method to handle your response to Reachability changes, eg.

    - (void)reachabilityChanged:(NSNotification*)notification
    {
      Reachability *notifier = [notification object];
      NSLog(@"%@", [notifier currentReachabilityString]);
    }
    

Note: If you press the Home button and unload the app, changes in Reachability should fire a notification immediately upon returning to the app.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!