我正在使用 AFNetworking (AFHTTPRequestOperation) 调用网络并取回数据。我需要使用 for 循环(卡片枚举)中的代码来检查每张卡片并取回数据,如果操作成功,我会获取有关卡片的信息,如果失败,我应该得到一个警报(使用警报视图)。问题是如果失败,我会收到多个警报(因为它在 for 循环中并且可能有许多卡)。如何仅在无法连接到网络时才显示一个警报?
我知道该操作是异步的,但无法使其正常工作。
下面的代码: -
- (void)verifyMobileDeviceStatus
{
[self fetchRequest];
[self.contentsArray enumerateObjectsUsingBlock:^(GCards *gCard, NSUInteger idx, BOOL * stop) {
NSURL *baseURL = nil;
baseURL = [NSURL URLWithString:BASE_URL_STRING];
NSString *soapBody = [NSString stringWithFormat:@"<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?><soapenv:Envelope xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"><soapenv:Header/><soapenv:Body><VerifyMobileDeviceStatus xmlns=\"http://tempuri.org/\"><Request><AuthToken>%@</AuthToken></Request></VerifyMobileDeviceStatus></soapenv:Body></soapenv:Envelope>", [gCard valueForKey:@"authToken"]];
NSLog(@" auth token =%@", [gCard valueForKey:@"authToken"]);
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:baseURL];
NSString *msgLength = [NSString stringWithFormat:@"%d", [soapBody length]];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[soapBody dataUsingEncoding:NSUTF8StringEncoding]];
[request addValue: msgLength forHTTPHeaderField:@"Content-Length"];
[request addValue:@"http://tempuri.org/VerifyMobileDeviceStatus" forHTTPHeaderField:@"SOAPAction"];
[request addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"success: %@", operation.responseString);
NSString *xmlString = [operation responseString];
[parser setGCard:gCard];
[parser parseXML:xmlString];
if([gCard.merchantStatus isEqualToString:MERCHANT_STATUS_ACTIVE])
{
gCard.isPremiumAccount = [NSNumber numberWithInt:1];
}
else
{
gCard.isPremiumAccount = [NSNumber numberWithInt:0];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[parser.delegate verifyDeviceStatusParserDidFailWithError:@"Error"];
NSLog(@"error: %@", [error userInfo]);
}];
[operation start];
}];
}
- (void)verifyDeviceStatusParserDidFailWithError:(NSString *)error
{
NSString *errorString = [NSString stringWithFormat:@"Error =%@", [error description]];
NSLog(@"Error parsing XML: %@", errorString);
BlockAlertView* alert = [BlockAlertView alertWithTitle:@"Connection Failed" message:@"Connection to web service Failed. Please try again."];
[alert addButtonWithTitle:NSLocalizedString(@"OK", nil) block:^{ }];
[alert show];
[activityIndicator stopAnimating];
self.navigationController.view.userInteractionEnabled = YES;
}
它会多次显示警报,如果它失败了,我只需要显示一次。
任何帮助,将不胜感激。