计算Swift中两个PFGeoPoints之间的距离

时间:2015-08-11 02:24:32

标签: ios swift parse-platform

我试图找到两个PFGeoPoints之间的英里距离;用户的当前位置和Parse中保存的位置。在我的代码中,我检索保存的位置并将其存储在itemLocation中。

紧接着,我使用geoPointForCurrentLocationInBackground找到用户的当前位置,并使用distanceInMiles比较两者之间的距离,并将值指定给名为distance的变量。

保存所有这些后,"距离" Parse中的字段仍然空白,因此无法保存。我在这里做错了什么?

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 个答案:

答案 0 :(得分:0)

1。以下是如何调试的想法,(我希望它对你的编码生涯有所帮助)

在块中设置一些“断点”,你可能会发现“geoPointForCurrentLocationInBackground”下的块永远不会被调用。

现在,你知道为什么没有保存PFObject。

下一步。搜索为什么geoPointForCurrentLocationInBackground永远不会运行

  1. 以下是答案:
  2. 您需要将以下键/值对添加到您应用的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>
    

    参考文献:

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