iOS 可达性指南

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3790957/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 17:47:20  来源:igfitidea点击:

Reachability Guide for iOS

iosiphonereachability

提问by esqew

Has anyone found a halfway decent guide to implementing Reachability on iOS?

有没有人找到在 iOS 上实现 Reachability 的半体面指南?

回答by enbr

I have implemented Reachability like this. Download https://developer.apple.com/library/content/samplecode/Reachability/Introduction/Intro.htmland add Reachability.h and .m to your project. Add the SystemConfiguration framework to your project. #import "Reachability.h" where you want to use it. Use this code.

我已经实现了这样的可达性。下载https://developer.apple.com/library/content/samplecode/Reachability/Introduction/Intro.html并将 Reachability.h 和 .m 添加到您的项目中。将 SystemConfiguration 框架添加到您的项目中。#import "Reachability.h" 在你想使用它的地方。使用此代码。

-(BOOL)reachable {
    Reachability *r = [Reachability reachabilityWithHostName:@"enbr.co.cc"];
    NetworkStatus internetStatus = [r currentReachabilityStatus];
    if(internetStatus == NotReachable) {
        return NO;
    }
    return YES;
}

When you want to check for reachability...

当您想检查可达性时...

if ([self reachable]) {
    NSLog(@"Reachable");
}
else {
    NSLog(@"Not Reachable");
}

Here is the example project that I made. http://dl.dropbox.com/u/3656129/ReachabilityExample.zip

这是我制作的示例项目。http://dl.dropbox.com/u/3656129/ReachabilityExample.zip

回答by yabtzey

I think the best way to check the availability of host address is by checking the results of NSURL Request.

我认为检查主机地址可用性的最佳方法是检查 NSURL 请求的结果。

NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:reqURL]];
NSURLResponse *resp = nil;
NSError *error = nil;
NSData *response = [NSURLConnection sendSynchronousRequest: theRequest returningResponse: &resp error: &error];
NSString *responseString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];

Using this bit of Code, if your device cannot reach the provided URL, it provides some output to the error variable, if it can access the URL Request, error is Nil.

使用这段代码,如果你的设备无法访问提供的 URL,它会向错误变量提供一些输出,如果它可以访问 URL 请求,则错误为零。

Reachability gives a positive output even if you URL packets can route out from your device and never reach the host server.

即使您的 URL 数据包可以从您的设备路由出去并且永远不会到达主机服务器,可达性也会提供积极的输出。