如何通过可达性检测网络变化?
我目前正在使用以下方法检查 viewDidLoad
上的网络连接:
-(BOOL)reachable {
ReachabilityDRC *r = [ReachabilityDRC reachabilityWithHostName:@"google.com"];
NetworkStatus internetStatus = [r currentReachabilityStatus];
if(internetStatus == NotReachable) {
return NO;
}
return YES;
}
但我也希望在网络发生变化时收到通知,例如 wifi 断开或 wifi 恢复,以便我可以进行相应的更改。
我该如何调整我的方法来做这样的事情?
I'm currently checking network connection on viewDidLoad
using this:
-(BOOL)reachable {
ReachabilityDRC *r = [ReachabilityDRC reachabilityWithHostName:@"google.com"];
NetworkStatus internetStatus = [r currentReachabilityStatus];
if(internetStatus == NotReachable) {
return NO;
}
return YES;
}
But I also want to be notified if there is a change of network, such as wifi dropped, or wifi is back, so I can make changes accordingly.
How can I adjust my method to do something like that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
1- 将
SystemConfiguration.framework
添加到您的项目中。2- 从 GitHub 下载以下文件
3- 添加这些项目中的文件
4- 在
YourViewController.h
中添加@class Reachability;
5- 在
YourViewController.h
中添加变量Reachability* internetReachable;
YourViewController.h
6- 在
YourViewController.m
中添加Reachability.h
7- 在
-(void)ViewDidLoad
中添加以下行code> 在YourViewController.m
8- 在
-(void)viewDidLoad
之后添加以下函数现在,每次互联网连接的变化您都会在控制台中看到登录。
1- add
SystemConfiguration.framework
to your project.2- Download following files from GitHub
3- Add these files in your projects
4- add
@class Reachability;
inYourViewController.h
5- add variable
Reachability* internetReachable;
inYourViewController.h
6- add
Reachability.h
inYourViewController.m
7- add following lines in
-(void)ViewDidLoad
inYourViewController.m
8- add following function after
-(void)viewDidLoad
Now every change of internet connection you will see log in console.
另一种可能的解决方案是在“application didfinishlaunching”中添加 NS 通知:
并在 checkForReachability 方法中执行以下操作:
Another possible solution is to add a NS Notification in "application didfinishlaunching":
and in checkForReachability method do this:
我使用了 Donoho Design Group 对 Reachability 类的出色扩展。它具有通知功能,可让您在网络状态发生变化时收到警报。
http://blog.ddg.com/?p=24
祝你好运
I've used the excellent extension to the Reachability class that the Donoho Design Group has put together. It has notifications that allow you to be alerted when the network status changes.
http://blog.ddg.com/?p=24
Good luck