iPhone reachability checking

被刻印的时光 ゝ 提交于 2019-11-26 12:04:32
Kendall Helmstetter Gelner

From your screen shot, it seems like you do not have Reachability added to your project. You must download Reachability from Apple:

https://developer.apple.com/library/content/samplecode/Reachability/Introduction/Intro.html

And add both .h and .m files to your project.

Update: You noted you have Reachability. But looking at the most recent version, I can see why you have the errors you listed - they changed the API and you are probably using sample code you found somewhere else. Try:

in .h file:

//import Reachability class
#import "Reachability.h"

// declare Reachability, you no longer have a singleton but manage instances
Reachability* reachability;

in .m file:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNetworkChange:) name:kReachabilityChangedNotification object:nil];

reachability = [Reachability reachabilityForInternetConnection];
[reachability startNotifier];

NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];

 if(remoteHostStatus == NotReachable) {NSLog(@"no");}
else if (remoteHostStatus == ReachableViaWiFi) {NSLog(@"wifi"); }
else if (remoteHostStatus == ReachableViaWWAN) {NSLog(@"cell"); }

.....

- (void) handleNetworkChange:(NSNotification *)notice
{

  NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];

   if(remoteHostStatus == NotReachable) {NSLog(@"no");}
else if (remoteHostStatus == ReachableViaWiFi) {NSLog(@"wifi"); }
else if (remoteHostStatus == ReachableViaWWAN) {NSLog(@"cell"); }
}
[reachability setHostName:@"http://www.google.com"];

Attention! I encountered the problem that it's always "NotReachable" if the http:// prefix is used.

Raphael

Here's the right code as it works for me today!!!

[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(handleNetworkChange:) name: kReachabilityChangedNotification object: nil];

reachability = [Reachability reachabilityForInternetConnection];

[reachability startNotifier];

NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];

if(remoteHostStatus == NotReachable) {NSLog(@"no");}
else if (remoteHostStatus == ReachableViaWiFi) {NSLog(@"wifi"); }
else if (remoteHostStatus == ReachableViaWWAN) {NSLog(@"cell"); }

Do you have the following code anywhere?

[reachability startNotifier];

if your reachability code is from apple's example, then you need to do that before it can start reporting status updates to you.

change this

reachability = [Reachability reachabilityForInternetConnection];

to this

reachability = [[Reachability reachabilityForInternetConnection] retain];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!