我正在尝试查询存储在Parse后端的PFGeoPoints数组。我有User表,并为其分配了数据,例如" location"," name"。 从我的应用程序发布后,所有内容都被发送到Parse并正确存储在后端。我在从Parse检索所有位置并将它们存储到地图上的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)")
}
}
}

答案 0 :(得分:1)
不像以前的评论者所说的那样将呼叫置于您的viewDidAppear()
方法中,您的位置可能为零,不会返回任何结果 - 我会使用某种跟踪器并将其放入您的didUpdateLocations()
MKMapView委托方法。在这里,我使用GCD的dispatch_once()
,这样当我第一次以合理的准确度找到我的位置时,我的代码就被执行了(在这里你将把你的电话调到Parse)。
声明GCD的跟踪变量
var foundLocation: dispatch_once_t = 0
现在在您的位置管理器的委托方法didUpdateLocations()
if userLocation?.location?.horizontalAccuracy < 2001 {
dispatch_once(&foundLocation, {
// Put your call to Parse here
})
}
PS。您还应该考虑在主线程上对UI进行任何更新。 Parse在后台线程上获取数据,虽然您可能永远不会看到问题,但在主线程上进行任何UI更改都是更安全和更好的习惯。您可以使用以下方法执行此操作:
dispatch_async(dispatch_get_main_queue(), {
// Put any UI update code here. For example your pin adding
}