从处理 Web 服务连接的对象中,当网络出现故障时,我将警报传递给使用 Web 服务对象的视图控制器。
网络服务对象:
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:[NSString stringWithFormat:@"Connection failed! You must be connected to a Wifi source to download data. Please reconnect to a Wifi source and try again later."] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles: nil];
NSDictionary *alertDict = [NSDictionary dictionaryWithObjectsAndKeys:alert, @"AlertView", nil];
[[NSNotificationCenter defaultCenter] postNotificationName:DisplayAlertNotification object:self userInfo:alertDict];
视图控制器:
- (void)displayAlert:(NSNotification *)notification {
NSDictionary *dict = [notification userInfo];
if ([[dict objectForKey:@"AlertView"] isKindOfClass:[UIAlertView class]]) {
UIAlertView *alert = [dict objectForKey:@"AlertView"];
NSNumber *theTag = [dict objectForKey:@"AlertTag"];
NSLog(@"%i", [theTag integerValue]);
alert.tag = [[dict objectForKey:@"AlertTag"] integerValue];
[alert show];
}
}
- (void)removeAlert:(NSNotification *)notification {
NSDictionary *dict = [notification userInfo];
if ([[dict objectForKey:@"AlertTag"] isKindOfClass:[NSNumber class]]) {
NSNumber *theTag = [dict objectForKey:@"AlertTag"];
UIAlertView *alert = (UIAlertView *)[self.view viewWithTag:[theTag integerValue]];
// Not sure why but my alert is nil at this point
[alert dismissWithClickedButtonIndex:0 animated:YES];
}
}
我还以相同的方式使用 removeAlert 方法以编程方式删除警报。这样做的目的是,如果网络出现故障,但用户尚未单击“确定”,然后网络恢复正常,我将关闭“网络失败”警报,并显示“网络恢复”警报。它可以工作,除非它解除警报并显示网络已恢复,一旦用户单击“网络恢复”上的“确定”,原来的网络故障只会恢复一次。如果用户在出现 Network Failed 时单击 Ok,则它永远不会恢复。
我是否以这种方式正确地解除了警报?谢谢。
编辑:我可以通过在 WebServiceObject 中保存一个引用并以这种方式关闭它来使其工作。