我正在尝试使用NSURLSessions
中的Objective C
获取JSON数据。我可以获取数据,但我无法将其保存到数组中以用作另一个tableview的数据源。我不确定发生了什么,我对Sessions不熟悉。此外,当我在完成块内部使用for循环时,我得到一个无限循环的Stop对象。我想使用NSURLSession,所以我也可以缓存数据,因为这些数据几乎没有变化,但可能每个月左右一次。我的代码如下。
-(NSMutableArray *)fetchStopListing {
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",kStopList, kApiKey]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request
completionHandler:^(NSData * data, NSURLResponse * response, NSError * error) {
if (!data) {
NSLog(@"Download Error: %@", error.localizedDescription);
//Create a UIAlertController
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Error" message:[NSString stringWithFormat:@"Error %@", error.localizedDescription] preferredStyle:UIAlertControllerStyleAlert];
//Create a UIAlerAction that can be added to the alert
UIAlertAction *ok = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:nil];
//Add UIAlertAction ok to UIAlertController
[alert addAction:ok];
} else {
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
NSArray *JSONArray = [JSON valueForKeyPath:@"stops.stop"];
//NSLog(@"Hey this is JSON Data %@", JSON);
self.stopsArray = [NSMutableArray new];
for (int i = 0; i < [JSONArray count] ;i++) {
float lat = [[JSONArray[i] objectForKey:@"stoplat"] floatValue];
float lng = [[JSONArray[i] objectForKey:@"stoplng"] floatValue];
NSString *stopNumber = [JSONArray[i] objectForKey:@"stopnumber"];
NSString *stoptitle = [JSONArray[i] objectForKey:@"stoptitle"];
Stops *newStop = [[Stops alloc] initWithStopLat:lat stopLong:lng stopNumber:stopNumber stopTitle:stoptitle];
//NSLog(@"This is th newStop: %@", newStop.stopTitle);
[self.stopsArray addObject:newStop];
for (Stops *stop in self.stopsArray) {
NSLog(@"Stoptitle: %@",stop.stopTitle);
}
}
}
}] resume];
NSLog(@"is this getting called");
//NSLog(@"%@",self.stopsArray[5]);
return self.stopsArray;
}