How to use reachability class to detect valid internet connection?(如何使用可达性类来检测有效的互联网连接?)
问题描述
我是 iOS 开发的新手,正在努力让reachability.h 类正常工作.这是我的视图控制器代码:
I'm new to iOS development and am struggling to get the reachability.h class to work. Here is my code for view controller:
- (void)viewWillAppear:(BOOL)animated
{
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(checkNetworkStatus:)
name:kReachabilityChangedNotification
object:nil];
internetReachable = [Reachability reachabilityForInternetConnection];
[internetReachable startNotifier];
}
- (void)checkNetworkStatus:(NSNotification *)notice {
NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
NSLog(@"Network status: %i", internetStatus);
}
看起来不错,但在运行应用程序并切换到该视图时,xcode 控制台中没有出现任何内容.
It looks ok but nothing is appearing in the xcode console when running the app and switching to that view.
我正在使用可达性 2.2 和 iOS 4.2.
I'm using Reachability 2.2 and iOS 4.2.
有什么明显的我做错了吗?
Is there something obvious that I am doing wrong?
推荐答案
已如果你想在一些代码执行之前检查可达性,你应该使用
EDITED: If you want to check reachability before some code execution you should just use
Reachability *reachability = [Reachability reachabilityForInternetConnection];
NetworkStatus internetStatus = [reachability currentReachabilityStatus];
if (internetStatus != NotReachable) {
//my web-dependent code
}
else {
//there-is-no-connection warning
}
您还可以在某处添加可达性观察者(即在 viewDidLoad 中):
You can also add a reachability observer somewhere (i.e. in viewDidLoad):
Reachability *reachabilityInfo;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(myReachabilityDidChangedMethod)
name:kReachabilityChangedNotification
object:reachabilityInfo];
当您不再需要可达性检测时(即在 dealloc 方法中),不要忘记调用 [[NSNotificationCenter defaultCenter] removeObserver:self];.
Don't forget to call [[NSNotificationCenter defaultCenter] removeObserver:self]; when you no longer need reachability detection (i.e. in dealloc method).
这篇关于如何使用可达性类来检测有效的互联网连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用可达性类来检测有效的互联网连接?
基础教程推荐
- iOS4 创建后台定时器 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
