按计算距离订购UITableView单元格(Parse)

时间:2015-01-03 09:52:01

标签: objective-c uitableview parse-platform

我在解析时创建的数据库有问题。我有一张桌子,向我展示各种各样的本地(一旦你从DB下载列表)多少英里的问题是我会订购它向上距离,但我不知道该怎么办。我用来计算距离的代码如下:

- (id)initWithCoder:(NSCoder *)aCoder
{
    self = [super initWithCoder:aCoder];
    if (self) {
        // Custom the table

        // The className to query on
        self.parseClassName = @"Ristoranti";

        // The key of the PFObject to display in the label of the default cell style
        self.textKey = @"NomeLocale";

        // Whether the built-in pull-to-refresh is enabled
        self.pullToRefreshEnabled = YES;

        // Whether the built-in pagination is enabled
        self.paginationEnabled = YES;

        // The number of objects to show per page
        self.objectsPerPage = 100;
    }
    return self;
}


- (void)viewDidLoad
{
    [super viewDidLoad];

    locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;
    locationManager.distanceFilter = kCLDistanceFilterNone;
    locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;

    if(IS_OS_8_OR_LATER) {

        [locationManager requestWhenInUseAuthorization];
        [locationManager requestAlwaysAuthorization];
    }

    [locationManager startUpdatingLocation];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(refreshTable:)
                                                 name:@"refreshTable"
                                               object:nil];
}

- (void)refreshTable:(NSNotification *) notification
{
    // Reload the recipes
    [self loadObjects];
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"refreshTable" object:nil];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

- (PFQuery *)queryForTable
{
    PFQuery *query = [PFQuery queryWithClassName:self.parseClassName];

    query.limit = 100;

    [query orderByAscending:@"createdAt"];

    return query;   
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object
{
    static NSString *simpleTableIdentifier = @"RecipeCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    if (cell == nil) {

            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
    }

    NSString *AntDef = [NSString stringWithFormat:@"%@", [object objectForKey:@"AnteprimaDefault"]];

    if ([AntDef isEqualToString:@"Null"])
    {   
        PFImageView *thumbnailImageView = (PFImageView*)[cell viewWithTag:100];
        thumbnailImageView.image = [UIImage imageNamed:@"ImageDefault.png"];
        thumbnailImageView.layer.cornerRadius = thumbnailImageView.frame.size.width / 2;
        thumbnailImageView.clipsToBounds = YES;
        thumbnailImageView.layer.borderWidth = 0.5;
        thumbnailImageView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    }

    else
    {   
        PFFile *thumbnail = [object objectForKey:@"Anteprima1"];
        PFImageView *thumbnailImageView = (PFImageView*)[cell viewWithTag:100];
        thumbnailImageView.image = [UIImage imageNamed:@"placeholder.jpg"];
        thumbnailImageView.file = thumbnail;
        thumbnailImageView.layer.cornerRadius = thumbnailImageView.frame.size.width / 2;
        thumbnailImageView.clipsToBounds = YES;
        [thumbnailImageView loadInBackground];
    }



    Lat = [[object objectForKey:@"Latitudine"] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    Long = [[object objectForKey:@"Longitudine"] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

    Latdouble = [Lat doubleValue];
    Longdouble = [Long doubleValue];


    NSArray *locations = [NSArray arrayWithObjects:[[CLLocation alloc] initWithLatitude:Latdouble longitude:Longdouble], nil];

    //NSLog(@"LOCATIONS COORDINATE: %@", locations);

    CLLocation *currentLocation = [[CLLocation alloc] initWithLatitude:locationManager.location.coordinate.latitude longitude:locationManager.location.coordinate.longitude];;
    CLLocation *nearestLoc = nil;
    CLLocationDistance nearestDis = FLT_MAX;

    for (CLLocation *location in locations) {
        CLLocationDistance distance = [currentLocation distanceFromLocation:location];

        for (CLLocation *location in locations) {
            distance = [currentLocation distanceFromLocation:location];
            if (nearestDis > distance) {
                nearestLoc = location;
                nearestDis = distance;
            }
        }

        text12 = [NSString  stringWithFormat:@"%.1f Km", nearestDis/1000];
    }

...
}

提前致谢:)

2 个答案:

答案 0 :(得分:1)

假设您Parse.com的回复数据为NSArray

我建议:

  • 请求。
  • NSArray
  • 进行排序
  • 重新加载数据。

使用块sortedArrayUsingComparator:^NSComparisonResult(id a, id b)

可以像这样对数组进行排序
NSArray *sortedArray;
sortedArray = [initialDataArray sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
   //Here do the method to compare if `a` is closer or `b` is closer
   YourParseObject *aObject = (YourParseObject *)a;
   YourParseObject *bObject = (YourParseObject *)b;
   //Get Latitude & Longitude from a and b.
   //return NSOrderedAscending or NSOrderedDescending according to which one of a or b is the closest, using your previous method I suppose to be working.

}];

所以sortedArray看起来像这样:

{
 YourParseObject the closest one
 YourParseObject the second closest one
 //...
 YourParseObject the farthest one.
}

一旦完成:

[yourTableView reloadData]

答案 1 :(得分:0)

我今天刚遇到这个问题,发现Parse.com已经实现了这个解决方案:

如果您使用的是Parse的PFQueryTableViewController.h,则需要将其添加到queryForTable方法中:

  
      
  • (PFQuery *)queryForTable {
  •   
 PFQuery *query = [PFQuery queryWithClassName:self.parseClassName];    
        [query whereKey:@"yourClassPFLocationField" nearGeoPoint:yourLocation];
    return query;
}

如果您不使用PFQueryTable,则同样适用,只需在加载查询时使用该排序方法即可。

所有内容都在PFQuery文档中:D