I am trying a little project where I get the current location coordinates, then by the current location I find coffee shops nearby and display them in a UITableView. So far I have managed to load the JSON script with the information, parse it into a dictionary, and display it in the UITableView. What I want to do now is try to order the information by 'distance' or by 'name' (alphabetically). How can I do that? Here is some code to show what I have done so far.
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
if (!self.didFindLocation) {
self.didFindLocation = YES;
[self.locationManager stopUpdatingLocation];
}
NSMutableArray *resultArray = [[NSMutableArray alloc] init];
CLLocation *crnLoc = [locations lastObject];
NSString *latitudeString = [NSString stringWithFormat:@"%.10f",crnLoc.coordinate.latitude];
NSString *longitudeString = [NSString stringWithFormat:@"%.10f",crnLoc.coordinate.longitude];
NSString *urlString = [NSString stringWithFormat:@"https://api.foursquare.com/v2/venues/search?client_id=ACAO2JPKM1MXHQJCK45IIFKRFR2ZVL0QASMCBCG5NPJQWF2G&client_secret=YZCKUYJ1WHUV2QICBXUBEILZI1DMPUIDP5SHV043O04FKBHL&ll=%@,%@&query=coffee&v=20140806&m=foursquare", latitudeString, longitudeString];
NSURL *url = [NSURL URLWithString:urlString];
NSData *jsonData = [NSData dataWithContentsOfURL:url];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSDictionary *responseDictionary = [dataDictionary objectForKey:@"response"];
NSDictionary *venueDictionary = [responseDictionary objectForKey:@"venues"];
for (NSDictionary *dict in venueDictionary) {
NSString *name = [dict objectForKey:@"name"];
NSDictionary *locationDictionary = [dict objectForKey:@"location"];
NSString *address = [NSString stringWithFormat: @"%@", [locationDictionary objectForKey:@"address"]];
if (address == nil) {
address = @"No address provided";
}
NSString *distance = [NSString stringWithFormat: @"%@", [locationDictionary objectForKey:@"distance"]];
if (distance == nil) {
distance = @"No coordinates provided";
}
NSLog(@"Name: %@ Address: %@ distance: %@", name, address, distance);
CoffeeStore *store = [[CoffeeStore alloc] initWithName:name address:address distance:distance];
[resultArray addObject:store];
}
self.storeArray = resultArray;
[self.tableView reloadData]; }
and
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
CoffeeStore *selectedStore = self.storeArray[indexPath.row];
cell.textLabel.text = selectedStore.name;
cell.detailTextLabel.text = selectedStore.distanceString;
return cell;
}