I have a Core Data database with latitude and longitude properties. Is there a way to use Core Location's getDistanceFrom:
method to find the five nearest locations to a CLLocation
obtained from the GPS? Do I have to load all the objects using Core Data and parse through them, using getDistanceFrom:
on each one or is there an easier way?
The persistent store should be located in the AppData > Library > Application Support directory. In this example you should see a SQLite database with extension . sqlite. It is possible that you don't see the persistent store in the Application Support directory.
Core Location provides services that determine a device's geographic location, altitude, and orientation, or its position relative to a nearby iBeacon device. The framework gathers data using all available components on the device, including the Wi-Fi, GPS, Bluetooth, magnetometer, barometer, and cellular hardware.
Core Data is a framework that you use to manage the model layer objects in your application. It provides generalized and automated solutions to common tasks associated with object life cycle and object graph management, including persistence.
Getting Started Core Data (CRUD) with Swift. Core Data is a graphical and persistence framework, which is used in Apple devices with operating systems macOS and iOS. Core Data was first introduced in Mac OS X 10.4 Tiger and iOS with iPhone SDK 3.0.
You will have to iterate through them one by one; as far as I know there is no other way to do it.
However, you can make this more efficient by using a bounding box when you get the items from core data - this will reduce the number of objects that will be returned.
i.e. Something like
float latMax = wantedLat + 1; float latMin = wantedLat - 1; float lngMax = wantedLng + 1; float lngMin = wantedLng - 1; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"lat > %f and lat < %f and lng > %f and lng < %f", latMin, latMax, lngMin, lngMax];
Though, depending on how much data you have and how closely it's spaced, you will want to use a different number than 1!
Sam
PS Also, I haven't taken into account the fact that longitude wraps!
You can't use CoreData to find the nearest object, but might want to narrow down the query by using a bounding box. To find the nearest object, you might prefer to use simply the difference in lat/long which is considerably faster than calculating the actual distances.
I had a similar question:
CoreData: Find minimum of calculated property
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With