Reputation: 1355
Hello I need help to select and display only the fruits which are 5km from the user's current location. I have to display them in table view cells.Here is my code:
@IBOutlet weak var LabelTest: UILabel!
var locationManager = CLLocationManager()
var lat = Double()
var long = Double()
var latitude = Double()
var longitude = Double()
struct Fruit {
let name : String
let location : CLLocation
let latitude : Double
let longitude: Double
let imageURL : NSURL
let description : String
func distanceTo(location:CLLocation) -> Int
{
let distanceMeters = location.distanceFromLocation(self.location)
let distanceKilometers = distanceMeters / 1000.00
return Int(round(100 * distanceKilometers) / 100)
}
}
var fruits = [Fruit]()
func parseFruits() {
if CalculateDistance() < 5 {
guard let url = NSBundle.mainBundle().URLForResource("cities", withExtension: "json"), jsonData = NSData(contentsOfURL: url) else {
print("Error finding JSON File")
return
}
let jsonObject = JSON(data: jsonData)
let fruitArray = jsonObject["fruits"].arrayValue
for aFruit in fruitArray {
let name = aFruit["Name"].stringValue
let latitude = aFruit["Latitude"] as! Double
let longitude = aFruit["Longitude"] as! Double
let location = CLLocation(latitude: latitude, longitude: longitude)
let imageURL = aFruit["Picture"].stringValue
let description = aFruit["Description"].stringValue
let fruit = Fruit(name: name,location: location,latitude:latitude,longitude: longitude, imageURL: NSURL(string:imageURL)!, description: description)
fruits.append(fruit)
}
self.tableView.reloadData()
}
}
override func viewDidLoad() {
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
}
super.viewDidLoad()
parseFruits()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location:CLLocationCoordinate2D = manager.location!.coordinate
lat = location.latitude
long = location.longitude
}
func CalculateDistance() -> Int{
let userLocation = CLLocation(latitude: lat, longitude: long)
let destinationLocation = CLLocation(latitude:latitude, longitude: longitude)// latitude and longitude from the json file
let distance = userLocation.distanceFromLocation(destinationLocation)
return roundToFive(distance)
}
private func roundToFive(x : Double) -> Int {
return 5 * Int(round(x / 5.0))
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print("Error")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return fruits.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: TableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell") as! TableViewCell
let fruit = fruits[indexPath.row]
cell.CellTitle.text = fruit.name
cell.CellDescription.text = fruit.description
let image = UIImage(data: NSData(contentsOfURL:(string: fruit.imageURL))!)
cell.CellImage.image = image
return cell
}
In the TableView Cells I have to display only the fruits which are 5km from the user's location. I tried to do something, but it seems that it isn't working. Any ideas how to fix it?
Upvotes: 0
Views: 58
Reputation: 38833
Just do it like this:
// Update your CalculateDistance method to the following
func CalculateDistance(lat: Double, long: Double) -> Int{
let userLocation = CLLocation(latitude: lat, longitude: long)
let destinationLocation = CLLocation(latitude:latitude, longitude: longitude)// latitude and longitude from the json file
let distance = userLocation.distanceFromLocation(destinationLocation)
return roundToFive(distance)
}
// When you parse your fruits, you can make the check if it´s within 5km then you can add it to your array or add it to a separate array
if (CalculateDistance(latitude, longitude) <= 5000{
fruits.append(fruit)
}
Upvotes: 1
Reputation: 295
What does your CalculateDistance method do? You should filter your array.
func shouldShowFruit(fruit: Fruit) -> Bool{
let userLocation = CLLocation(latitude: lat, longitude: long)
let destinationLocation = CLLocation(latitude:fruit.latitude, longitude: fruit.longitude)
let distance = userLocation.distanceFromLocation(destinationLocation)
return distance < 5000
}
Call this method for every item in your array and if it returns false remove from array.
Upvotes: 0