开发者

iPhone Multiple Alerts Called after a network connection check

开发者 https://www.devze.com 2023-03-12 11:08 出处:网络
Searching for an answer, some had noted the issue but no one resolved it. I simply want to the user to be notified if a network connection change has occurred (ie loss of network). The code below work

Searching for an answer, some had noted the issue but no one resolved it. I simply want to the user to be notified if a network connection change has occurred (ie loss of network). The code below works but I get multiple alerts, usually 3. I understand the reason why it may happen because of multiple internal calls being made for accuracy but I can't seem to have only one alert display and that's that. I've tried to use a BOOL to detect if an alert is already showing (alertshowing) but it still doesn't help. Thanks for your thoughts.

- (void)applicationDidBecomeActive:(UIApplication *)application {
    ////NSLog(@"DidBecomeActive");

    [self performSelector:@selector(getNetworkConnection) withObject:nil afterDelay:5.0];

}


-(void)getNetworkConnection
{
    Reachability *r = [Reachability reachabilityWithHostName:@"www.google.com"];

    NetworkStatus internetStatus = [r currentReachabilityStatus];

        if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN))
        {
            if (!self.alertShowing) {
            UIAlertView *myAlert = [[[UIAlertView alloc] initWithTitle:@"No Internet Connection" message:@"This app require an internet connection via WiFi or cellular network to work." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil] autorelease];
            self.alertShowing = YES;
       开发者_如何转开发     [myAlert show];
            }
        }       
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    self.alertShowing = NO;
}


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

The above line of code should only be called a single time for the entire app.
If you invoke this line of code in a function which is called many times, the notification also shows many alerts.

So I recommend you to create a singleton class which will be live throughout the app and call the above line of code in the area where object for singleton class is created.

Note:- above line of code should be invoked only once for the entire app

0

精彩评论

暂无评论...
验证码 换一张
取 消