在我的应用程序中,我想实现一个功能,我的应用软件中有一个按钮,当iOS设备的网络丢失时,这个按钮应该自动变为禁用,当网络再次正常可用时,按钮应该变为启用。
这应该在每次设备网络连接丢失或可用时自动完成。
我没有得到任何方式或任何类型的线索来实现这个功能,如果有人知道如何在iOS应用程序中实现这个功能的话,请帮助我。
提前感谢。
我相信您正在使用可达性类进行网络状态检测。因此,您可以使用以下代码片段注册网络状态更改检测
[[NSNotificationCenter defaultCenter]addObserver:自选择器:@selector(reachabilityHasChanged:)名称:kReachabilityChangedNotification对象:nil];
现在,您可以为可达性对象调用startNotificationer
[self.internetReachability startNotifier];
在方法reachabilityHasChanged中,您可以捕获所有3个状态的状态更改,即ReachableViaWiFi、ReachableViaWWAN和NotReachable。现在,在无法访问的情况下,您可以禁用按钮,如:
myButton.enabled=否;
从可到达的状态,您可以再次启用它。
您可以使用NSTimer,在该定时器中,您可以在每2秒后调用Reachability类的BOOL函数,并使其重复YES,返回true或false
NSTimer* internetTimer;
internetTimer=[NSTimer scheduledTimerWithTimeInterval:2.0f target:self selector:@selector(checkInternet) userInfo:nil repeats:YES];
-(void)checkInternet{
if([self isInternetAvailable])
{
//enable button
}
else
{
//disable button
}
}
-(BOOL)isInternetAvailable()
{
Reachability *networkReachability = [Reachability reachabilityForInternetConnection];
NetworkStatus networkStatus = [networkReachability currentReachabilityStatus];
return !(networkStatus == NotReachable);
}
你可以在这里找到可达性类.h和.m。只需在项目中添加这两个文件。https://github.com/tonymillion/Reachability
如果您处于ARC开启模式,您可能还必须为.m 设置fno标志
您也可以在某个地方添加可达性观测器(即在viewDidLoad中):
Reachability *reachabilityInfo;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(myReachabilityDidChangedMethod)
name:kReachabilityChangedNotification
object:reachabilityInfo];
您必须阅读上提供的苹果文档和源代码https://developer.apple.com/library/ios/samplecode/Reachability/Introduction/Intro.html
在Reachability/APLViewController.m中,您将找到所有答案,即如何观察网络更改通知以及如何更新按钮状态(启用/禁用),甚至可以更新用户界面