Ios 如何在'query.limit'后面限制解析查询的结果`

Ios 如何在'query.limit'后面限制解析查询的结果`,ios,arrays,swift,parse-platform,Ios,Arrays,Swift,Parse Platform,我有8个假用户,包括我在内,在解析中有不同的位置。如果用户按下我地图上的注释,我希望获得一个带有他们的user.username的数组,与他们中选择的一个直接聊天,通过prepareforsgue将user.username发送到我的下一个NewChatVC接收器var。为了实现这一点,我尝试创建一个数组closeUsersArray,首先从更接近的人中选择10个人。以公里为单位的距离过滤器似乎不错,但当我尝试填充数组时,在控制台中我得到了很多重复,而只有8个名称: self.closeUser

我有8个假用户,包括我在内,在解析中有不同的位置。如果用户按下我地图上的注释,我希望获得一个带有他们的user.username的数组,与他们中选择的一个直接聊天,通过
prepareforsgue
将user.username发送到我的下一个
NewChatVC
接收器var。为了实现这一点,我尝试创建一个数组
closeUsersArray
,首先从更接近的人中选择10个人。以公里为单位的距离过滤器似乎不错,但当我尝试填充数组时,在控制台中我得到了很多重复,而只有8个名称:

self.closeUsersArray.append(user.username!) //MARK: Test
或一个组/数组,或填充了这8个名称的重复项,这种情况发生在:

println("this is the array of users * \(self.closeUsersArray) *") //MARK: Test
更新

我发现在
locationManager
code with
println(“evaluates”)
中多次求值,调用
displayLocationInfo
并调用
createAnnotations
多次。我想我应该试着清除条件,可能太多了

下面是我的档案,提前谢谢

import UIKit
import MapKit
import CoreLocation
import Parse

class MapViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate, UIActionSheetDelegate {


    @IBOutlet weak var mapView: MKMapView!
    @IBOutlet weak var segmentedControl: UISegmentedControl!

    let locationManager = CLLocationManager()
    let kDefaultKmForUserOnMap = 50.0                   //default value

    var limitNumberForQueryResults = 10

    var closeUsersArray:[String] = []                   //MARK: Test

    let defaults = NSUserDefaults.standardUserDefaults()
    var withinKms : Double!



    override func viewDidLoad()
    {
        super.viewDidLoad()


        //MARK: checks if the variable is nil, if yes, attributes a value
        if defaults.doubleForKey("withinKms") <= 0 {
            defaults.setDouble(kDefaultKmForUserOnMap, forKey: "withinKms")
            defaults.synchronize()
            withinKms = defaults.doubleForKey("withinKms")
            println("MapViewController - viewDidLoad - var kKmRadiusForUsersOnMap was never set before, so now is set to  \(withinKms) ")
        } else {
            withinKms = defaults.doubleForKey("withinKms")
            println("MapViewController - viewDidLoad - else occurred and var test is \(withinKms)")
        }



        self.locationManager.delegate = self
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
        self.locationManager.requestWhenInUseAuthorization()
        self.locationManager.startUpdatingLocation()

        self.mapView.showsUserLocation = true

    }


    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)

    }



    override func viewDidAppear(animated: Bool)
    {
        super.viewDidAppear(animated)

        self.segmentedControl.selectedSegmentIndex = 0

        withinKms = self.defaults.doubleForKey("withinKms")
        println("MapViewController - viewDidAppear - radius shown on map is * \(withinKms) * ")

    }





    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

        if segue.identifier == "fromMapToNewChats" {

            //MARK: Hint - this is the standard way to pass data to a NOT embedded VC

            var nextVC : NewChatsFromHomeVC = segue.destinationViewController as! NewChatsFromHomeVC
            nextVC.calledFromVC = "MapViewController"
            nextVC.receivedReceiver = "Specific User"

//            //        nextVC.filterToParse = self.channleKeywordReceived

        }

    }



    //************************************************

    //MARK: send message by touching an annotation

    func mapView(mapView: MKMapView!, didSelectAnnotationView view: MKAnnotationView!) {

        println("anotation pressed: \(view.annotation.title)")

        self.performSegueWithIdentifier("fromMapToNewChats", sender: self)

    }

    //************************************************




    // MARK: - Location Delegate Methods

    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!)
    {
        let point = PFGeoPoint(latitude:manager.location.coordinate.latitude, longitude:manager.location.coordinate.longitude)
        let location = locations.last as! CLLocation

        let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
        let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 1, longitudeDelta: 1))

        self.mapView.setRegion(region, animated: true)

        CLGeocoder().reverseGeocodeLocation(manager.location, completionHandler: {(placemarks, error)->Void in

            if (error != nil)
            {
                println("Error: " + error.localizedDescription)
                return
            }

            if placemarks.count > 0
            {
                let pm = placemarks[0] as! CLPlacemark
                self.displayLocationInfo(pm, point: point)
                println("evaluates 3")
            }
            else
            {
                println("Error with the data.")
            }
        })
    }





    func displayLocationInfo(placemark: CLPlacemark, point: PFGeoPoint)
    {
        self.locationManager.stopUpdatingLocation()

        self.createAnnotations(point, address: "\(placemark.locality) \(placemark.administrativeArea) \(placemark.postalCode) \(placemark.country)")
    }





    func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!)
    {
        println("Error: " + error.localizedDescription)
    }



//    timelineMessageDataArray.removeAll(keepCapacity: true)          //erase previus contents
//    println("timelineData cleared")


    // MARK: - Create Annotation

    func createAnnotations(point: PFGeoPoint, address: String)
    {

        var query = PFUser.query()


        query?.whereKey("location", nearGeoPoint: point, withinKilometers: withinKms)
        query?.orderByAscending("location")  //MARK:  Put list in order

        query?.limit = self.limitNumberForQueryResults


        query?.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in

            if error == nil
            {
                for(var i = 0; i < objects!.count; i++)
                {
                    let user = objects![i] as! PFUser
                    var myHomePin = MKPointAnnotation()
                    let userPoint = user["location"] as! PFGeoPoint
                    myHomePin.coordinate = CLLocationCoordinate2DMake(userPoint.latitude, userPoint.longitude)
                    myHomePin.title = user.username

                    myHomePin.subtitle = address
                    self.mapView.addAnnotation(myHomePin)

//                    self.closeUsersArray.append(user.username!) //MARK: Test

                }






//                    println("this is the array of users * \(self.closeUsersArray) *") //MARK: Test
            }
            else
            {
                println("Error: " + error!.localizedDescription)
            }

        })

    }






    // MARK: - Action Delegate

    func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int)
    {
        switch(buttonIndex)
        {
        case 0: //Destructive button
            break
        case 1: // 25.0 Km
            //            NSUserDefaults.standardUserDefaults().setDouble(25.0, forKey: "withinKms")
            self.defaults.setDouble(50.0, forKey: "withinKms")
            self.defaults.synchronize()
            self.locationManager.startUpdatingLocation()
            break;
        case 2: // 50.0 Km
            self.defaults.setDouble(100.0, forKey: "withinKms")
            self.defaults.synchronize()
            self.locationManager.startUpdatingLocation()
            break;
        case 3: // 100.0 Km
            self.defaults.setDouble(200.0, forKey: "withinKms")
            self.defaults.synchronize()
            self.locationManager.startUpdatingLocation()
            break;
        case 4: // 200.0 Km
            self.defaults.setDouble(300.0, forKey: "withinKms")
            self.defaults.synchronize()
            self.locationManager.startUpdatingLocation()
            break;
        default:
            break;
        }
    }






    // MARK: - Actions

    @IBAction func homeAction(sender: AnyObject)
    {
        self.dismissViewControllerAnimated(true, completion: nil)
    }

    @IBAction func indexChanged(sender: UISegmentedControl)
    {
        switch segmentedControl.selectedSegmentIndex
        {
        case 0:
            println("map clicked")      //MARK: this one never evaluates!
        case 1:
            self.performSegueWithIdentifier("showListView", sender: self)
            println("showListView clicked")
        default:
            break;
        }
    }




    @IBAction func radiusAction(sender: UIButton)
    {
        //        UIActionSheet(title: nil, delegate: self, cancelButtonTitle: "cancel", destructiveButtonTitle: nil, otherButtonTitles: "25.0 Miles", "50.0 Miles", "100.0 Miles", "200.0 Miles").showInView(self.view)
        UIActionSheet(title: nil, delegate: self, cancelButtonTitle: "cancel", destructiveButtonTitle: nil, otherButtonTitles: "50 Km", "100 Km", "200 Km", "300 Km").showInView(self.view)
    }



    @IBAction func profileButton(sender: UIBarButtonItem) {
        //        let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("ProfileNavControllerID") as? UIViewController
        //
        //        self.presentViewController(vc!, animated: true, completion: nil)
        let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("ProfileNavControllerID") as! UIViewController
        self.presentViewController(vc, animated: true, completion: nil)

    }



}
导入UIKit
导入地图套件
导入核心定位
导入解析
类MapViewController:UIViewController、MKMapViewDelegate、CLLocationManagerDelegate、UIActionSheetDelegate{
@ibvar映射视图:MKMapView!
@IBOutlet弱var分段控制:UISegmentedControl!
让locationManager=CLLocationManager()
让kDefaultKmForUserOnMap=50.0//默认值
var limitNumberForQueryResults=10
var closeUsersArray:[字符串]=[]//标记:测试
让defaults=NSUserDefaults.standardUserDefaults()
var withinKms:双重!
重写func viewDidLoad()
{
super.viewDidLoad()
//标记:检查变量是否为nil,如果是,则指定一个值
如果为默认值。doubleForKey(“withinKms”)在中无效
如果(错误!=nil)
{
println(“错误:+错误。本地化描述)
回来
}
如果placemarks.count>0
{
设pm=placemarks[0]为!CLPlacemark
自我显示位置信息(pm,点:点)
println(“3”)
}
其他的
{
println(“数据错误”)
}
})
}
func displayLocationInfo(地点标记:CLPlacemark,点:PFGeoPoint)
{
self.locationManager.stopUpdatengLocation()
self.createAnnotations(点,地址:“\(placemark.locality)\(placemark.administrativeArea)\(placemark.postalCode)\(placemark.country)”)
}
func locationManager(管理器:CLLocationManager!,错误:N错误!)
{
println(“错误:+错误。本地化描述)
}
//timelineMessageDataArray.removeAll(keepCapacity:true)//擦除previus内容
//println(“时间线数据已清除”)
//标记:-创建注释
func createAnnotations(点:PFGeoPoint,地址:字符串)
{
var query=PFUser.query()
查询?.whereKey(“位置”,近地点:点,带测高仪:带测高仪)
query?.orderByAscending(“位置”)//标记:按顺序排列列表
query?.limit=self.limitNumberForQueryResults
查询?.FindObjectsInBackgroundithBlock({(对象,错误)->中的Void
如果错误==nil
{
对于(变量i=0;ifor nearbyUser in objects {

let user = nearbyUser.objectForKey("username")
var myHomePin = MKPointAnnotation()
let userPoint = nearbyUser.objectForKey("location") as! PFGeoPoint
myHomePin.coordinate = CLLocationCoordinate2DMake(userPoint.latitude, userPoint.longitude)
myHomePin.title = ("\(user)")

myHomePin.subtitle = address
self.mapView.addAnnotation(myHomePin)

self.closeUsersArray.append(user) //MARK: Test