0

我正在尝试检查设备是否已连接到互联网。如果没有,则会弹出警报,用户需要按“重试”才能重试。在我的代码中,第一次弹出警报视图时,我按“重试”,然后第二次弹出警报,它会在一秒钟后自行关闭。但假设只有当我按下“重试”时才会关闭。

这是我的代码:

在.h中:

#import <UIKit/UIKit.h>

@class Reachability;

@interface ViewController : UIViewController{
    Reachability* internetReachable;
    Reachability* hostReachable;

    UIAlertView *networkAlert;
}

-(void) checkNetworkStatus;

@end

以 .m 为单位:

#import "ViewController.h"
#import "Reachability.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    networkAlert = [[UIAlertView alloc]initWithTitle: @"Unstable Network Connection"
                                         message: @"Unstable network connection."
                                        delegate: self
                               cancelButtonTitle: nil
                               otherButtonTitles: @"Try Again", nil];

    [self checkNetworkStatus];

 }

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


 -(void) checkNetworkStatus
{
    NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
    switch (internetStatus)
    {
        case NotReachable:
         {
            NSLog(@"The internet is down.");
            [networkAlert show];
            break;
         }
        case ReachableViaWiFi:
        {
            NSLog(@"The internet is working via WIFI.");        
            break;
        }
        case ReachableViaWWAN:
        {
            NSLog(@"The internet is working via WWAN.");

            break;
        }
    }
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0)
    {
        NSLog(@"user pressed Button Indexed 0");
        // Any action can be performed here
        [self checkNetworkStatus];

    }
}

@end

对不起我的英语,提前谢谢你!!!

4

1 回答 1

0

我能够复制您看到的问题,这与您实际上是在告诉 alertView 显示它何时仍在屏幕上并处于被解雇过程中的事实有关。解除 alertView 的时间会有一点延迟,当他们点击Try Again按钮时,您会同时解除和呈现相同的警报视图。

解决此问题的方法是删除您拥有的警报视图变量,在这种情况下确实不需要保留它。使用简单的方法来呈现消息,并在需要时调用它,并且因为它每次都是一个单独的警报实例,所以您不必担心同时显示/隐藏它。

- (void)showInternetConnectionMessage {
    [[[UIAlertView alloc]initWithTitle: @"Unstable Network Connection" message: @"Unstable network connection." delegate: self cancelButtonTitle: nil otherButtonTitles: @"Try Again", nil] show];
}
于 2014-08-25T14:26:13.210 回答