Objective c PFUser当前位置按最近升序位置排序数组

Objective c PFUser当前位置按最近升序位置排序数组,objective-c,sorting,parse-platform,Objective C,Sorting,Parse Platform,在过去的4天里,我们一直在编写这段代码,试图调用PFUser位置,然后调用该位置。从接收到的位置,我希望阵列的照片,以升序排序的基础上,用户的位置。但是,用户位置未正确填充,最终为PFUser location nil (NSArray *)caches { PFGeoPoint *userGeoPoint = [PFUser currentUser][@"location"]; PFQuery *query = [Cache query]; [query whereKey:@

在过去的4天里,我们一直在编写这段代码,试图调用PFUser位置,然后调用该位置。从接收到的位置,我希望阵列的照片,以升序排序的基础上,用户的位置。但是,用户位置未正确填充,最终为PFUser location nil

(NSArray *)caches {

  PFGeoPoint *userGeoPoint = [PFUser currentUser][@"location"];

  PFQuery *query = [Cache query];

  [query whereKey:@"location" nearGeoPoint:userGeoPoint withinMiles:20];
  query.limit = 20;

  NSMutableArray *photoArray = [[query findObjects] mutableCopy];

  [PFGeoPoint geoPointForCurrentLocationInBackground:^(PFGeoPoint *geoPoint, 
  NSError *error){

    if (!error) {

      [[PFUser currentUser] setObject:geoPoint forKey:@"currentLocation"];
      [[PFUser currentUser] saveInBackground];
    }
  }];

  return photoArray;
}

您尝试这样做的方式存在一些问题:

您正在使用findObjects同步获取查询结果。这将阻塞主线程,直到返回结果。您应该改用findObjectsInBackgroundWithBlock。 因为您使用的是异步方法来获取位置和 同步方法,则在保存用户位置之前,您的查询将始终完成。 每次获取照片时,您都会查询用户的位置,而不是使用保存的值。理想情况下,您可能希望在应用程序启动时提前保存用户的位置,以便在您进行查询时已经设置好。您甚至可以设置一个计时器,以每分钟或您选择的时间间隔更新用户的位置。 您正在查询位置列,但正在保存当前位置。确保使用相同的列名来设置和检索位置。 这就是我推荐的方法。启动应用程序时调用此功能以更新用户在后台的位置:

- (void)updateUserLocation {
    [PFGeoPoint geoPointForCurrentLocationInBackground:^(PFGeoPoint *geoPoint, NSError *error) {
        if (!error) {
            [[PFUser currentUser] setObject:geoPoint forKey:@"location"];
            [[PFUser currentUser] saveInBackground];
        }
    }];
}
- (void)getPhotosInBackground:(void (^)(NSArray *photos, NSError *error))block {
    PFGeoPoint *userGeoPoint = [PFUser currentUser][@"location"];

    PFQuery *query = [Cache query];
    [query whereKey:@"location" nearGeoPoint:userGeoPoint withinMiles:20];
    [query setLimit:20];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        block(objects, error);
    }];
}
然后,当您需要获取照片时,调用此函数在后台获取照片:

- (void)updateUserLocation {
    [PFGeoPoint geoPointForCurrentLocationInBackground:^(PFGeoPoint *geoPoint, NSError *error) {
        if (!error) {
            [[PFUser currentUser] setObject:geoPoint forKey:@"location"];
            [[PFUser currentUser] saveInBackground];
        }
    }];
}
- (void)getPhotosInBackground:(void (^)(NSArray *photos, NSError *error))block {
    PFGeoPoint *userGeoPoint = [PFUser currentUser][@"location"];

    PFQuery *query = [Cache query];
    [query whereKey:@"location" nearGeoPoint:userGeoPoint withinMiles:20];
    [query setLimit:20];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        block(objects, error);
    }];
}

请格式化代码,使其易于阅读。