目标:将返回的所有 NSDictionaries 与一个公共键值“延迟”组合到一个 NSMutablearry 中,我可以使用它来比较结果(真或假)以在地图上放置绿色或红色图钉。
此代码以 JSON 格式返回机场数据,我将其转换为所请求机场的字典。有许多键,但在这部分代码中,我只对一个“延迟”感兴趣,我想将它组合成一个 NSMutablearry。
因为我一次只能请求一个机场,所以它单独带回每个请求的机场,我得到 9 组数据。我想要的是 9 个延迟键都在一个数组中,用于 9 个不同的机场。
`- (void)configureData
{
self.airportCodes = [[NSArray alloc] initWithObjects:
@"ATL",
@"BOS",
@"BWI",
@"CLT",
@"CVG",
@"DEN",
@"EWR",
@"ORD",
@"SFO",
nil];
NSUInteger airportCount = self.airportCodes.count;
for(int i=0; i < airportCount;i++){
NSURL *url = [self urlWithSearchText:[self.airportCodes objectAtIndex: i]];
NSString *jsonString = [self performAirportRequestWithURL:url];
if (jsonString == nil) {
[self showNetworkError];
}
NSDictionary *dictionary = [self parseJSON:jsonString];
if (dictionary == nil) {
[self showNetworkError];
}
self.airportDelays = [[NSMutableArray alloc] initWithCapacity:9];
[self parseDelay:dictionary];
//NSLog(@"AP Delays %@",self.airportDelays);
}
return;
}
- (void)parseDelay:(NSDictionary *)dictionary
{
//self.delay = [dictionary objectForKey:@"delay"];
[self.airportDelays addObject:dictionary];
NSLog(@"AP Delays %@",self.airportDelays);
return;
}
- (NSURL *)urlWithSearchText:(NSString *)searchText
{
NSString *escapedSearchText =
[searchText stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *urlString =
[NSString stringWithFormat:
@"http://services.faa.gov/airport/status/%@? format=application/json", escapedSearchText];
NSURL *url = [NSURL URLWithString:urlString];
return url;
}
- (NSString *)performAirportRequestWithURL:(NSURL *)url
{
NSError *error;
NSString *resultString = [NSString stringWithContentsOfURL:
url encoding:NSUTF8StringEncoding error:&error];
if (resultString == nil) {
NSLog(@"Download Error: %@", error);
return nil;
}
return resultString;
}
- (void)showNetworkError
{
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:@"Whoops..."
message:@"There was an error reading
from the FAA Server. Please try again."
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alertView show];
}
- (NSDictionary *)parseJSON:(NSString *)jsonString
{
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
id resultObject = [NSJSONSerialization JSONObjectWithData:data options:
kNilOptions error:&error];
if (resultObject == nil) {
NSLog(@"JSON Error: %@", error);
return nil;
if (![resultObject isKindOfClass:[NSDictionary class]]) {
NSLog(@"JSON Error: Expected dictionary");
return nil;
}
}
return resultObject;
}
@end`