iOS编程中的可达性AlertView

时间:2012-11-22 19:45:12

标签: ios xcode ipad

因此,我发出警报视图,检测是否存在活动的互联网连接。

这是代码:

- (void)viewDidLoad
{
    [super viewDidLoad];

    [[NSNotificationCenter defaultCenter] addObserver:self
    selector:@selector(reachabilityChanged:)
    name:kReachabilityChangedNotification
    object:nil];
    Reachability * reach = [Reachability reachabilityWithHostname:@"www.google.com"];
    reach.reachableBlock = ^(Reachability * reachability)
    { 
     dispatch_async(dispatch_get_main_queue(), ^{
     blockLabel.text = @"";  
     });
    };
    reach.unreachableBlock = ^(Reachability * reachability)
    {
     dispatch_async(dispatch_get_main_queue(), ^{
     blockLabel.text = @"You are not connected to the Internet";
     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Please connect to Internet"
     message:nil
     delegate:self
     cancelButtonTitle:nil
     otherButtonTitles:nil];
     UIActivityIndicatorView *progress= [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(125, 50, 30, 30)];
     progress.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
            [alert addSubview:progress];
            [progress startAnimating];
            [alert show]; 
        });
    };
    [reach startNotifier];
    // Do any additional setup after loading the view, typically from a nib.
}

所以我的应用程序检测到是否有互联网连接。但问题是,如果我在iPhone上打开互联网并打开应用程序,它仍然说没有互联网连接。我该怎么办......

3 个答案:

答案 0 :(得分:1)

我通过使用通知解决了这个问题.. 参考代码

-(void)reachabilityChanged:(NSNotification*)note
{
    Reachability * reach = [note object];

    if([reach isReachable])
    {
        notificationLabel.text = @"Notification Says Reachable";
        NSLog(@"Internet is Up");
    }
    else
    {
        notificationLabel.text = @"Notification Says Unreachable";
        NSLog(@"Internet is Down");
    }
}

答案 1 :(得分:0)

您可以通过注册可访问性通知来实现对主机可访问性(或互联网连接)的不间断检查。

关于如何执行此操作的最佳示例之一可以在SO上找到:How to check for an active Internet Connection on iPhone SDK?

这样您的应用就会知道主机是否可以访问。

答案 2 :(得分:0)

你的稀疏代码没有说明什么,因为它甚至看起来你的Reachability类是Apple的SystemConfiguration API的Reachability示例代码包装器,你可以在http://developer.apple.com/library/ios/#samplecode/Reachability/Introduction/Intro.html找到它

最简单和最明确的检查只是针对特定网址的未缓存的NSURLRequest(不仅仅是一个主机名,它仅测试DNS解析是否正常工作,这不是一个明确的测试,甚至可以缓存)