繁体   English   中英

如何获取用户的当前位置,执行本地地理查询,然后将结果应用于PFQueryTableViewController?

[英]How can I get the user's current location, perform a local geo query and then apply the results to a PFQueryTableViewController?

我一直在研究以下代码,最终感到困惑! 提取此代码的目的是捕获用户的当前位置,在10公里半径内搜索点,然后通过PFQueryTableView列出它们。

由于我的困惑,我的代码分为两部分。 第一部分确实检索了我期望的结果数量,因为关于对象计数的println语句反映出它为我通过模拟器调试工具设置的当前GPS位置找到了一项。

然后,该函数的第二部分基于固定位置进行类似的查询,但这并不是我希望它工作的方式。

理想情况下,如果我仅使用geoPointForCurrentLocationInBackground块就能做到这一点。

问题是,我该如何工作? 我正在学习来自不同开发背景的Swift和IOS开发。

override func queryForTable() -> PFQuery! {

    PFGeoPoint.geoPointForCurrentLocationInBackground {
      (point:PFGeoPoint!, error:NSError!) -> Void in
      if error == nil {
        var query = PFQuery(className: "Town")
        query.limit = 10
        query.whereKey("gps", nearGeoPoint: point, withinKilometers: 10.0)
        query.findObjectsInBackgroundWithBlock{
          (objects: [AnyObject]!, error: NSError!) -> Void in
          if (error == nil) {
            println(objects.count)
          }
        }
      }
    }

    let userGeoPoint = PFGeoPoint(latitude:40.0, longitude:-30.0)

    var query = PFQuery(className:"Town")
    // Interested in locations near user.
    query.whereKey("gps", nearGeoPoint:userGeoPoint, withinKilometers: 5.0)
    // Limit what could be a lot of points.
    query.limit = 10
    // Final list of objects
    //let placesObjects = query2.findObjects()
    return query
  }

您在这里遇到的问题是,用户位置的确定是异步发生的,但是您需要从该方法同步返回一个查询(因此您的方法可能会在拥有用户位置之前返回查询)。 我建议您重组代码以完成一些事情。

  1. 较早地获取用户位置,例如在viewDidLoad()view[Will/Did]Appear() ,并在有位置时重新加载tableView。
  2. 如果您不知道用户的位置,则返回给出0个结果的查询(或使用默认位置,或忽略位置)。 这里的适当行为是特定于应用程序的。

因此,您将需要以下类似的内容。

class MyViewController: PFQueryTableViewController {
  var usersLocation: PFGeoPoint? {
    didSet {
      // This will reload the tableview when you set the users location. 
      // Handy if you want to keep updating it.
      if (tableView != nil) {
        tableView.reloadData()
      }
    }
  }

  override func viewDidLoad() {
    super.viewDidLoad()
    PFGeoPoint.geoPointForCurrentLocationInBackground { point, error in
      if error == nil {
        self.usersLocation = point
      }
    }
  }

  override func queryForTable() -> PFQuery! {
    var query = PFQuery(className:"Town")
    // If we don't have a location, just query without it.
    if let location = usersLocation {
      query.whereKey("gps", nearGeoPoint:location, withinKilometers: 5.0)
    }
    query.limit = 10
    return query
  }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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