ios 在 Objective C 中检查 Internet 连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/477852/
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 15:35:01  来源:igfitidea点击:

Checking For Internet Connectivity in Objective C

objective-ciostwitter

提问by lewsid

I've been working through the Stanford iPhone Coding course and currently hooking into the Twitter API. What I'd like to do is accurately handle two error conditions: One for when the username is invalid, and another for when the device is not currently connected to the internet. Unfortunately, as it stands, the best I can surmise is whether or not the return from the API is nil or not - which is the case for both conditions.

我一直在学习斯坦福 iPhone 编码课程,目前正在使用 Twitter API。我想要做的是准确处理两种错误情况:一种用于用户名无效时,另一种用于设备当前未连接到互联网时。不幸的是,就目前而言,我能推测的最好结果是 API 的返回值是否为零 - 这两种情况都是如此。

What I'm looking for is a line or two of code that can check for a connection before attempting any fetch of remote data. I could sift through the Apple documentation but I figured: Why not put the question to you guys for my benefit and perhaps that of others?

我正在寻找的是一两行代码,可以在尝试获取任何远程数据之前检查连接。我可以筛选 Apple 文档,但我想:为什么不为了我和其他人的利益向你们提出这个问题呢?

Additional info: Using Objective-C and the iPhone SDK in XCode.

附加信息:在 XCode 中使用 Objective-C 和 iPhone SDK。

回答by August

Take a look at Apple's sample code. The Reachability project shows how to detect a connection.

看看苹果的示例代码。Reachability 项目展示了如何检测连接。

http://developer.apple.com/iphone/library/samplecode/Reachability/index.html

http://developer.apple.com/iphone/library/samplecode/Reachability/index.html

回答by Jason

That code works, but doesn't always create the desired result.

该代码有效,但并不总是创建所需的结果。

The way that the TCP stack on the iPhone works is very different from what should be expected. With the "Reachability" code, sometimes a network connection will be present, but will not be reliably detected. However, launching MobileSafari then reattempting to check connectivity with "Reachability" code will result in the correct result.

iPhone 上 TCP 堆栈的工作方式与预期的非常不同。使用“可达性”代码,有时会出现网络连接,但无法可靠地检测到。但是,启动 MobileSafari 然后重新尝试使用“Reachability”代码检查连接将导致正确的结果。

The way that I have found most effective in determining network connectivity is to run a NSURLConnection check when the application loads, in a separate thread. Make a call to a URL that you know will return something like "Yes" (i.e. HTML file on your server or something). Then check to be sure the returned result is equal to the static text. That way, you know that the NSURLConnection stack is reaching out properly, as opposed to the "Reachability" code that does not quite work consistently.

我发现确定网络连接最有效的方法是在应用程序加载时在单独的线程中运行 NSURLConnection 检查。调用一个你知道会返回类似“是”的 URL(即你的服务器上的 HTML 文件或其他东西)。然后检查以确保返回的结果等于静态文本。这样,您就知道 NSURLConnection 堆栈正在正确伸出,而不是“可达性”代码不能完全一致地工作。

回答by Colin Wheeler

You'll need to read in the error codes and respond as best you can. I've had some experience with this essentially it may depend on what service you are interacting with but with delicious.com I get error -1012 for bad user/passwd which if you look it up is

您需要阅读错误代码并尽可能做出响应。我在这方面有过一些经验,这可能取决于您正在与之交互的服务,但是对于美味的.com,我收到错误 -1012 错误用户/密码,如果您查找它是

NSURLErrorUserCancelledAuthentication =     -1012,

though clearly that wording is misleading, though I can consistently replicate putting in bad user/passwd and getting that error code. Technically the iPhone is never not connected to the internet unless you are in some strange region that has problems with data connection. I see also there is an error code

尽管显然措辞具有误导性,但我可以始终如一地复制输入错误的用户/密码并获取该错误代码。从技术上讲,iPhone 永远不会不连接到互联网,除非您在某个奇怪的地区,数据连接有问题。我也看到有一个错误代码

NSURLErrorNotConnectedToInternet =      -1009,

I would go through NSURLError.h(and there are more like that)

我会通过NSURLError.h(还有更多类似的)

NSURLErrorUnsupportedURL =          -1002,
NSURLErrorCannotFindHost =          -1003,
NSURLErrorCannotConnectToHost =         -1004,
NSURLErrorNetworkConnectionLost =       -1005,

etc...

等等...

all you need to do is get a reference to the NSError object you passed in & check it's error code like so

您需要做的就是获取对您传入的 NSError 对象的引用并检查它的错误代码,如下所示

//NSError *returnedError

if([returnedError code] == kERROR_CODE_BAD_USERNAME_OR_PASSWORD)

the constant is something i've defined in my own source code that is essentially -1012

常量是我在自己的源代码中定义的,本质上是 -1012

回答by Raj

this works for me and is taken from apple seismic xml project:

这对我有用,取自苹果地震 xml 项目:

- (BOOL)isDataSourceAvailable
{
    static BOOL checkNetwork = YES;
    if (checkNetwork) { // Since checking the reachability of a host can be expensive, cache the result and perform the reachability check once.
        checkNetwork = NO;

        Boolean success;    
        const char *host_name = "twitter.com"; // your data source host name

        SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, host_name);
        SCNetworkReachabilityFlags flags;
        success = SCNetworkReachabilityGetFlags(reachability, &flags);
        _isDataSourceAvailable = success && (flags & kSCNetworkFlagsReachable) && !(flags & kSCNetworkFlagsConnectionRequired);
        CFRelease(reachability);
    }
    return _isDataSourceAvailable;
}

回答by Raj

reachability is separate class through you can access the code

可达性是单独的类,通过您可以访问代码

   Reachability *curReach = [Reachability reachabilityForInternetConnection];
NetworkStatus netStatus = [curReach currentReachabilityStatus];
switch (netStatus)
{
    case NotReachable:
    {
        UIAlertView *connectionAlert = [[UIAlertView alloc] init];
        [connectionAlert setTitle:@"Error"];
        [connectionAlert setMessage:@"Please check your network connection."];
        [connectionAlert setDelegate:self];
        [connectionAlert setTag:1];
        [connectionAlert addButtonWithTitle:@"Back"];
        [connectionAlert show];

        break;
    }
    case ReachableViaWWAN:
    {


    }
    case ReachableViaWiFi:
    {
    }
}

回答by borisdiakur

When using Apple's Reachability bear in mind that you can find yourself being connected via WWAN (ReachableViaWWAN) or WiFi (ReachableViaWiFi) without being connected to the internet even when you try to reach some host like google.com or apple.com (maybe a caching issue). I ended up calling my own server and getting back a digit - the best solution in my case at least.

使用 Apple 的 Reachability 时请记住,即使您尝试访问 google.com 或 apple.com 等主机(可能是缓存问题)。我最终调用了我自己的服务器并取回了一个数字 - 至少在我的情况下是最好的解决方案。

回答by Nitin Malguri

-(BOOL)returnInternetConnectionStatus{
    ReachabilityLattest *reach = [ReachabilityLattest reachabilityForInternetConnection];
    NetworkStatus internetStatus = [reach currentReachabilityStatus];
    if ((internetStatus != NotReachable)) {
        return TRUE;
    } else {
        return FALSE;
    }
}

回答by Noah Witherspoon

What's your current connection code look like? If you're using NSURLConnection +sendSynchronousRequest:returningResponse:error:, then you just need to pass the address of an NSError variable and check that thereafter; with connectionWithRequest:delegate:, you should implement -connection:didFailWithError:in the delegate.

您当前的连接代码是什么样的?如果你正在使用NSURLConnection +sendSynchronousRequest:returningResponse:error:,那么你只需要传递一个 NSError 变量的地址并在之后检查它;使用connectionWithRequest:delegate:,您应该-connection:didFailWithError:在委托中实现。