简体   繁体   中英

How to disable segue when there is no internet connection for iOS app?

To check internet connectivity, I am thinking of updating by AppDelegate with:

  1. SystemConfiguration.framework
  2. Reachability.h

To stop segue, I am thinking of using:

- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender

I only want to show alert for no internet connection when user taps a UIButton.

What exactly should I do under

- (void)prepareForSegue:(NSStoryboardSegue *)segue sender:(id)sender

I have registered for notification under viewDidLoad method in each ViewController where I want to implement internet connectivity checks

[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(reachabilityChanged:) name: kReachabilityChangedNotification object: nil];

reachabilityChanged

- (void) reachabilityChanged: (NSNotification* )note
{
    Reachability* curReach = [note object];
    NSParameterAssert([curReach isKindOfClass: [Reachability class]]);

    NetworkStatus netStatus = [curReach currentReachabilityStatus];
    switch (netStatus)
    {
        case ReachableViaWWAN:
        {
            break;
        }
        case ReachableViaWiFi:
        {
            break;
        }
        case NotReachable:
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"We are unable to make a internet connection at this time. Some functionality will be limited until a connection is made." delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
            [alert show];   
            [alert release];
            break;
        }
    }
}

In your class interface, declare:

@property (nonatomic) BOOL isReachable;

In your reachabilityChanged method:

- (void)reachabilityChanged: (NSNotification* )note
{
    Reachability* curReach = [note object];
    NSParameterAssert([curReach isKindOfClass: [Reachability class]]);

    NetworkStatus netStatus = [curReach currentReachabilityStatus];
    switch (netStatus)
    {
        case ReachableViaWWAN:
        { 
            self.isReachable = YES;
            break;
        }
        case ReachableViaWiFi:
        {
            self.isReachable = YES;
            break;
        }
        case NotReachable:
        {
            self.isReachable = NO;
            break;
        }
    }
}

Then, check if connected to the internet in the shouldPerformSegueWithIdentifier method.

- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender
{
  if ([identifier isEqualToString:YOUR_IDENTIFIER]) {
    if (!self.isReachable) {
       return NO;
    }
  }
return YES;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM