简体   繁体   中英

Calculating distance between two PFGeoPoints in Swift

I'm trying to find the distance in miles between two PFGeoPoints; the user's current location and a saved location in Parse. In my code, I'm retrieving the saved location and storing it in itemLocation.

Immediately after, I am finding the user's current location using geoPointForCurrentLocationInBackground and comparing the distance between the two with distanceInMiles and assigning the value to the variable named distance.

After saving all this, the "distance" field in Parse still comes up blank so it's not saving. What am I doing wrong here?

func retrieveItemInfo() {

var items = PFObject(className: "Items")
var query = PFQuery(className: "Items")
query.orderByDescending("createdAt")

query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) -> Void in

    if error == nil {
        if let objects = objects {
            for (index, title) in enumerate(objects) {
                let itemLocation = (title as! PFObject)["location"] as! PFGeoPoint

                PFGeoPoint.geoPointForCurrentLocationInBackground({ (geoPoint: PFGeoPoint?, error: NSError?) -> Void in
                    if error == nil {
                        var userLocation = geoPoint
                        var distance = userLocation?.distanceInMilesTo(itemLocation)
                        items.setValue(distance, forKey: "distance")
                        items.saveInBackgroundWithBlock({ (success: Bool, error: NSError?) -> Void in
                            if success {

                            } else {
                                println("Error")
                            }

                        })
                    }


               })

1 . Here is the idea how to debug, ( i hope it will be helpful in your coding career)

set some "break point" in block, and you may find the block under "geoPointForCurrentLocationInBackground" NEVER be called.

now, you know why the PFObject is not saved.

next step. search why geoPointForCurrentLocationInBackground never run

  1. Here is the answer :

you need to add the following key/value pair to your app's info.plist:

<key>NSLocationWhenInUseUsageDescription</key>

<string>We want to send your location data to the NSA, please allow access to location services. (replace this text with whatever you want the dialog to say)</string>

References:

https://stackoverflow.com/a/26139620/5158750

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM