iOS 编程中的可达性警报视图



所以我让警报视图检测是否有活动的互联网连接。

这是代码:

- (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上打开互联网并打开应用程序,它仍然说没有互联网连接。我该怎么办...

好吧,

我通过使用通知来解决问题。参考代码

-(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");
    }
}

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

有关如何执行此操作的最佳示例之一可以在SO上找到:如何在iPhone SDK上检查有效的互联网连接?

这样,您的应用将始终知道主机是否可访问。

不知道你的稀疏代码做了什么,因为它甚至看起来不像你的可达性类是 Apple 围绕系统配置 API 的可达性示例代码包装器,你可以在 http://developer.apple.com/library/ios/#samplecode/Reachability/Introduction/Intro.html

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

最新更新