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

标签 ios swift parse-platform pfquery

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

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

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

理想情况下,如果我可以仅使用 geoPointForCurrentLocationInBackground block 来完成此操作,那就太棒了。

问题是,我该如何让它发挥作用?我来自不同的开发背景,正在学习 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
  }

}

关于ios - 我如何获取用户的当前位置,执行本地地理查询,然后将结果应用到 PFQueryTableViewController?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27760958/

相关文章:

ios - 在 UIScrollView 内的可缩放 UIIMageView 周围绘制一个 1 像素宽的框

ios - Swift3 - 单例共享 UItextfield 值不更新第二次

ios - 在 UIViewController 之间切换时会发生什么类型的内存问题?

ios - React-native 升级相关类型错误

ios - 从 parse 迁移到 azure 不适用于移动应用程序

javascript - 解析云函数失败,出现错误 141

iphone - 导航栏继承方法列表

ios - 在 tableview 中滚动时 UIActivityIndi​​cator 不会向上移动

ios - 在应用程序中无需登录即可使用解析功能

swift - 如何在Segue之前添加Admob Interstitial?