这是我在我的应用中使用Reachability的代码:
- (void) handleNetworkChange:(NSNotification *)notice
{
NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];
if(remoteHostStatus == NotReachable) {
UIAlertView *alertnew = [[UIAlertView alloc] initWithTitle:@"No Internet Connection!" message:@"Your device lost internet connection!"
delegate:self
cancelButtonTitle:@"Close"
otherButtonTitles:@"Dismiss", nil];
[alertnew show];
} else if (remoteHostStatus == ReachableViaWWAN) {
//if connected to the Network
UIAlertView *alertre = [[UIAlertView alloc] initWithTitle:@"Internet Connection!" message:@"Your device re-connected to the internet!"
delegate:self
cancelButtonTitle:nil
otherButtonTitles:@"Ok!", nil];
[alertre show];
} else if (remoteHostStatus == ReachableViaWiFi) {
//if connected to Wi-Fi
UIAlertView *alertre = [[UIAlertView alloc] initWithTitle:@"Internet Connection!" message:@"Your device re-connected to the internet!"
delegate:self
cancelButtonTitle:nil
otherButtonTitles:@"Ok!", nil];
[alertre show];
}
}
我想在用户丢失互联网以及获得回复时提醒用户。但我遇到的问题是,当用户使用iPhone(具有持续的网络连接)并且他们连接到Wi-Fi时,他们会在已经连接时收到警报。因此,如果他们没有互联网连接并连接到Wi-Fi,我只想提醒他们。此代码适用于没有数据计划的iPod和iPad,但问题出在iPhone上。我可以做些什么来编辑它,并使它只显示一个或另一个的警报?
我为最后一次警报尝试了此代码:
else if (remoteHostStatus == ReachableViaWiFi && !(remoteHostStatus == ReachableViaWWAN)) {
//if connected to Wi-Fi but without Network
UIAlertView *alertre = [[UIAlertView alloc] initWithTitle:@"Internet Connection!" message:@"Your device re-connected to the internet!"
delegate:self
cancelButtonTitle:nil
otherButtonTitles:@"Ok!", nil];
[alertre show];
}
但这并没有解决问题...
答案 0 :(得分:3)
代码逻辑中的基本错误是您将三个独立的状态视为两个状态。 Apple NetworkStatus
示例中的Reachability
由此处显示的enum
定义:
typedef enum {
NotReachable = 0,
ReachableViaWiFi,
ReachableViaWWAN
} NetworkStatus;
因为你基本上想要一个BOOL
(可到达或不可用)。只需将当前网络状态与NotReachable
进行比较即可。因此,对于ReachableViaWiFi
或ReachableViaWWAN
,BOOL
为YES
。
BOOL reachable = (_reachability.currentReachabilityStatus != NotReachable); // underbar added for good ivar style.
现在你只需要处理你有WiFi的情况并转移到手机或反之亦然。在这种情况下,您必须跟踪呼叫之间的状态。添加名为BOOL
的{{1}} ivar。然后在观察者方法中比较新值。
_reachable
警告:未经请求的建议
关于这些-(void)reachabilityDidChange:(NSNotification *)note{
BOOL reachable = (_reachability.currentReachabilityStatus != NotReachable);
if (reachable != _reachable){
// State Changed. Inform the user if necessary.
if (reachable){
// Connected.
} else {
// Lost connection.
}
}
_reachable = reachable;
}
概念的最后一点说明。警报基本上是对用户尖叫。关于重新连接的警报基本上大喊“嘿!现在一切都好!”。我想建议观看WWDC2012会议221,他们谈到常见的设计缺陷。大约35分钟他们开始讲警报。很明显,他们正试图引导开发人员尽可能地避免使用警报。