I have 8 fake users, including me, with different locations on Parse. If user presses on an annotation on my map, I'd like to get an array with their user.username to open a direct chat with the choosen one among them sending the user.username to my next NewChatVC
receiver
var via prepareForSegue
. In order to achieve this, I'm try'n to create an array closeUsersArray
with first, for say, ten people selected among closer ones. Distance filter in km seems to be fine, but when I try to fill my array, in the console I get many repetitions instead only 8 names with:
我有8个假用户,包括我,在Parse上有不同的位置。如果用户在我的地图上按下注释,我想获得一个带有user.username的数组,以便与选择的人员进行直接聊天,通过prepareForSegue将user.username发送到我的下一个NewChatVC接收器var。为了达到这个目的,我试着先创建一个数组closeUsersArray,比如说,从更近的人中选出10个人。以km为单位的距离过滤器似乎很好,但是当我尝试填充我的数组时,在控制台中我得到了很多重复,而只有8个名字:
self.closeUsersArray.append(user.username!) //MARK: Test
or a group/array or filled with repetitions of those 8 names this happens with:
或者一个组/数组或者重复这8个名称,这种情况发生在:
println("this is the array of users * \(self.closeUsersArray) *") //MARK: Test
update
更新
I discovered that in locationManager
code with println("evaluates")
evaluates multiple times, calling displayLocationInfo
with calls createAnnotations
multiple times. I think that I should try to clear conditions, maybe are too many
我发现在带有println(“evaluateates”)的locationManager代码中多次计算,多次调用displayLocationInfo调用createAnnotations。我认为我应该尝试清除条件,也许是太多了
below my file, thanks in advance
在我的文件下面,提前谢谢
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)
}
}
1 个解决方案
#1
0
Not sure if this would solve the problem but maybe changing your for
loop might help. Try this:
不确定这是否可以解决问题但是改变你的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
}
}
Try something like that maybe
尝试类似的东西
#1
0
Not sure if this would solve the problem but maybe changing your for
loop might help. Try this:
不确定这是否可以解决问题但是改变你的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
}
}
Try something like that maybe
尝试类似的东西