ios - 如何限制Parse上查询的结果在 `query.limit`后面

标签 ios arrays swift parse-platform

我有 8 个假用户,包括我在内,在 Parse 上有不同的位置。如果用户按下我的 map 上的注释,我想获取一个包含其 user.username 的数组,以打开与其中选择的用户的直接聊天,并将 user.username 发送到我的下一个 NewChatVC receiver var 通过 prepareForSegue。为了实现这一目标,我尝试创建一个数组 closeUsersArray,首先从较接近的人中选择 10 个人。以 km 为单位的距离过滤器似乎没问题,但是当我尝试填充数组时,在控制台中我得到了很多重复,而不是只有 8 个名称:

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

或一个组/数组或充满这 8 个名称的重复,发生这种情况:

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

更新

我发现在 locationManager 代码中使用 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)

    }



}

最佳答案

不确定这是否可以解决问题,但更改您的 for 循环可能会有所帮助。试试这个:

for 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

}

也许可以尝试类似的事情

关于ios - 如何限制Parse上查询的结果在 `query.limit`后面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32967993/

相关文章:

PHP AES256 加密 => RNCryptor RNDecryptor 返回空白/HMAC 不匹配

ios - UIButton 没有名为 setTranslatesAutoresizingMaskIntoConstraints 的成员

ios - 二进制数据允许外部存储 - 错误 : Compilation failed for data model at path

java - 对象数组的深拷贝

c - 将给定列表中的所有数字以随机顺序分配到二维数组中

ios - UIPageViewController 中的 UIImageView 大小调整问题

ios - Xcode 将一个框架链接到另一个框架

iphone - 在多线程中运行时 CoreText 崩溃

Mysql使用连接和数组匹配

ios - 与核心图像的色彩平衡