我正在尝试查询存储在 Parse 后端的 PFGeoPoints 数组。我有用户表,其中分配有数据,例如“位置”、“名称”。 从我的应用程序发布后,所有内容都会发送到 Parse,并正确存储在后端。我在从 Parse 检索所有位置并将它们存储到 map 上的 MKAnnotation 中时遇到问题。 在我的代码下方找到
import UIKit
import Parse
import CoreLocation
import MapKit
class mapViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
@IBOutlet var mapUsers: MKMapView!
var MapViewLocationManager:CLLocationManager! = CLLocationManager()
var currentLoc: PFGeoPoint! = PFGeoPoint()
override func viewDidLoad() {
super.viewDidLoad()
// ask user for their position in the map
PFGeoPoint.geoPointForCurrentLocationInBackground {
(geoPoint: PFGeoPoint?, error: NSError?) -> Void in
if let geoPoint = geoPoint {
PFUser.currentUser()? ["location"] = geoPoint
PFUser.currentUser()?.save()
}
}
mapUsers.showsUserLocation = true
mapUsers.delegate = self
MapViewLocationManager.delegate = self
MapViewLocationManager.startUpdatingLocation()
mapUsers.setUserTrackingMode(MKUserTrackingMode.Follow, animated: false)
}
override func viewDidAppear(animated: Bool) {
let annotationQuery = PFQuery(className: "User")
currentLoc = PFGeoPoint(location: MapViewLocationManager.location)
annotationQuery.whereKey("Location", nearGeoPoint: currentLoc, withinMiles: 10)
annotationQuery.findObjectsInBackgroundWithBlock {
(PFUser, error) -> Void in
if error == nil {
// The find succeeded.
print("Successful query for annotations")
let myUsers = PFUser as! [PFObject]
for users in myUsers {
let point = users["Location"] as! PFGeoPoint
let annotation = MKPointAnnotation()
annotation.coordinate = CLLocationCoordinate2DMake(point.latitude, point.longitude)
self.mapUsers.addAnnotation(annotation)
}
} else {
// Log details of the failure
print("Error: \(error)")
}
}
}
最佳答案
与其将调用放入您的 viewDidAppear()
方法中 - 正如之前的评论者所说,您的位置可能为零,不返回任何结果 - 我会使用某种跟踪器并将其放入您的didUpdateLocations()
MKMapView 委托(delegate)方法。在这里,我使用 GCD 的 dispatch_once()
,以便在第一次以合理的精度找到我的位置时,执行我的代码(在这里您将调用 Parse)。
声明GCD的跟踪器变量
var foundLocation: dispatch_once_t = 0
现在在位置管理器的委托(delegate)方法 didUpdateLocations()
if userLocation?.location?.horizontalAccuracy < 2001 {
dispatch_once(&foundLocation, {
// Put your call to Parse here
})
}
附言。您还应该考虑在主线程上对 UI 进行任何更新。 Parse 在后台线程上获取该数据,虽然您可能永远不会发现问题,但在主线程上进行任何 UI 更改更安全,也是一个好习惯。您可以使用以下方法执行此操作:
dispatch_async(dispatch_get_main_queue(), {
// Put any UI update code here. For example your pin adding
}
关于ios - 在 map 解析中显示所有用户的地理点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33430845/