Sorting by distance?

I'm trying to put together an app that sorts some records by their location field. Specifically it should sort from closest to furthest from the user's location.


I found a reference to the sortdescriptor named CKLocationSortDescriptor, and here's the text fro the class description:


---

During sorting, the sort descriptor computes the distance between the value in the

relativeLocation 
parameter and the location value found in the specified key of each record. It then sorts the records in ascending order using the distance between the two points. You cannot change the sort order.

---


Sounds exactly like what I need, but I can't seem to get it to work. I created a relativeLocation object as a fixed latitude/longitude position. Then I set up the predicate as true, and then used this code for the query:


        let query = CKQuery(recordType: "Trade", predicate: predicate)
        query.sortDescriptors = [CKLocationSortDescriptor(key: "Location", relativeLocation: fixedLocation)]
        // Create the query operation
        let queryOperation = CKQueryOperation(query: query)
        queryOperation.desiredKeys = ["Location", "Name"]
        queryOperation.queuePriority = .VeryHigh
        queryOperation.resultsLimit = 50


Unfortunately when I run the app, the listing is sorted in the order of the date last modified (last edited at the top). It's not sorted at all based on distance to the fixedLocation I put in. I can only assume I'm not understanding the proper usage of this function.


What am I doing wrong here?

According to documentation you are doing it right.


But I see the described behaviour using CloudKit.JS as well so it might be a bug.

This code is working for me. (But, surprisingly, it seems the searches get more 'accurate' with time - last night there were many ordering errors. This morning there were just a few ordering erros and tonight there are no ordering errors.)



CLLocation *home=[[CLLocation alloc] initWithLatitude:[[myParameterDictionary objectForKey:@"Home Latitude"] doubleValue] longitude:[[myParameterDictionary objectForKey:@"Home Longitude"] doubleValue]];

float radiusInMeters=10000;

NSPredicate *predicate=[NSPredicate predicateWithFormat:@"distanceToLocation:fromLocation:(HomeLocation,%@) < %f",home,radiusInMeters];

CKQuery *query=[[CKQuery alloc] initWithRecordType:@"Rides" predicate:predicate];

query.sortDescriptors =[NSArray arrayWithObject:[[CKLocationSortDescriptor alloc] initWithKey:@"HomeLocation" relativeLocation:home]];

[publicDatabase performQuery:query inZoneWithID:nil completionHandler:^(NSArray *results, NSError *error){

// code for handling results

}];

Sorting by distance?
 
 
Q