Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

iphone - Using Reachability for Internet *or* local WiFi?

I've searched SO for the answer to this question, and it's not really addressed, at least not to a point where I can make it work.

I was originally only checking for Internet reachability, using:

self.wwanReach = [Reachability reachabilityWithHostName:@"www.apple.com"];
[wwanReach startNotifer];

I now need to support a local WiFi connection (in the absence of reaching the Internet in general), and when I found +reachabilityForLocalWiFi, I also noticed there was +reachabilityForInternetConnection. I figured I could use these, instead of hard-coding "www.apple.com" in there, but alas, when I use:

self.wwanReach = [Reachability reachabilityForInternetConnection];
[wwanReach startNotifer];
self.wifiReach = [Reachability reachabilityForLocalWiFi];
[wifiReach startNotifer];

the reachability callback that I've set up "never" gets called, for values of "never" up to 10, 12, 15 minutes or so (which was as long as my patience lasted. (User's patience will be much less, I'm sure.) Switching back to +reachabilityWithHostName: works within seconds. I also tried each "pair" individually, in case there was an issue with two notifiers in progress simultaneously, but that made no difference.

So: what is the appropriate way to determine reachability to either the Internet/WWAN or a local Wifi network (either one, or both)?

[This particular use case is an iPhone or iPad connecting to a Mac mini computer-to-computer network; I'm sure other situations apply.]

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use this function to check if wifi is on

- (BOOL)isWifiOn {
    Reachability* wifiReach = [Reachability reachabilityForLocalWiFi];

    NetworkStatus netStatus = [wifiReach currentReachabilityStatus];
    return (netStatus==ReachableViaWiFi);
}

similar code can be used to check reachabilityForInternetConnection but you have to check

(netStatus==ReachableViaWiFi)

if you care that it's over wifi AND

(netStatus==ReachableViaWWAN)

if you care that it's over WWAN


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...