Location Query in Parse TableView

2019-09-15 17:22发布

问题:

I have a PFQueryTableView which is supposed to gather the 10 closest store locations and display them in order of proximity. I query the tableview like so:

    - (PFQuery *)queryForTable {
    PFQuery *query = [PFQuery queryWithClassName:@"TopToday"];
    query.limit = 7;
    CLLocation *currentLocation = locationManager.location;
    PFGeoPoint *userLocation =
    [PFGeoPoint geoPointWithLatitude:currentLocation.coordinate.latitude
                           longitude:currentLocation.coordinate.longitude];

    return query;
}

The above code works fine, just gathers 7 random locations in no particular order. However, when I add this line:

[query whereKey:@"location" nearGeoPoint:userLocation withinMiles:50];

It just returns a blank default tableview. Does anyone have any thoughts I why the query does not work with the location line?

回答1:

My guess is that the query is being run before your location manager returns a valid location.

I'd create a new property for the current geopoint;

@property (nonatomic, strong) PFGeoPoint *currentGeoPoint;

Then override loadObjects to make sure the geo point actually exists before the query runs.

- (void)loadObjects
{
    if (!self.currentGeoPoint)
    {
        [PFGeoPoint geoPointForCurrentLocationInBackground:^(PFGeoPoint *geo, NSError *error)
         {
             self.currentGeoPoint = geo;
             [super loadObjects];
         }];
    }
    else
    {
        [super loadObjects];
    }
}

And finally reference the currentGepoint in your query.

- (PFQuery *)queryForTable
{
    PFQuery *query = [PFQuery queryWithClassName:@"TopToday"];
    query.limit = 7;
    [query whereKey:@"location" nearGeoPoint:self.currentGeoPoint withinMiles:50];
    return query;
}