I'm trying to save venues into a NSArray
. Venue is an array in an NSDictionary
Response. I would like an NSArray
with all the venues so I can populate a table.
NSURL *url = [[NSURL alloc] initWithString:@"https://api.foursquare.com/v2/venues/search?ll=40.7,-74&query=dog&limit=10"];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSDictionary *responseData = [JSON objectForKey:@"response"];
self.venues = responseData[@"venues"];
[self.tableView setHidden:NO];
[self.tableView reloadData];
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(@"Request Failed with Error: %@, %@", error, error.userInfo);
}];
[operation start];
Four squares partial
response: {
venues: [{
id: "4ea2c02193ad755e37150c15"
name: "The Grey Dog"
contact: {
phone: "+12129661060"
formattedPhone: "+1 212-966-1060"
}
location: {
address: "244 Mulberry St"
crossStreet: "btwn Spring & Prince St"
lat: 40.723096
lng: -73.995774
distance: 2595
postalCode: "10012"
city: "New York"
state: "NY"
country: "United States"
cc: "US"
}
You do not need a new array to hold all the Venues.
First create a global NSDictionary
like:
NSDictionary* venuesDict;
@property (nonatomic, retain) NSDictionary* venuesDict;
and synthesise it. You can then assign it in you code above like so:
venuesDict = [[JSON objectForKey:@"response"] objectForKey:@"venues"];
NSLog(@"%@", venuesDict); //everything should work up to here!
Presuming the NSLog prints the output as you posted in you question (but with venues as the first object), you can populate a table like this:
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [[venuesDict objectForKey:@"venues"] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
cell.textLabel.text = [[venuesDict objectForKey@"venues"] objectForKey:@"name"];
return cell;
}