1

What I am aiming for is that when the user clicks a button, I want the code to check if they are near the location then they get points, I am just unsure where to put that information

class ViewController: UIViewController ,CLLocationManagerDelegate {

    @IBOutlet weak var map: MKMapView!
    let manager = CLLocationManager()

    @IBAction func getPoints(_ sender: Any) {
    //not sure what to add here, check the ...
    }

    override func viewDidLoad()
    {
        super.viewDidLoad()
        manager.delegate = self
        manager.desiredAccuracy = kCLLocationAccuracyBest
        manager.requestWhenInUseAuthorization()
        manager.startUpdatingLocation()
    }

//to show the map
    func locationManager(_ manager: CLLocationManager,        didUpdateLocations locations: [CLLocation])
    {
        let location = locations[0]
        let span:MKCoordinateSpan = MKCoordinateSpanMake(0.01, 0.01)
        let myLocation:CLLocationCoordinate2D =     CLLocationCoordinate2DMake(location.coordinate.latitude,      location.coordinate.longitude)
        let region:MKCoordinateRegion =     MKCoordinateRegionMake(myLocation, span)
        map.setRegion(region, animated: true)
        self.map.showsUserLocation = true

   //do i put this (the code below) under the @IBAction

        let userLocation = locations.last! as CLLocation
        let desiredLocation = CLLocation(latitude: 50.000000,     longitude: -50.000000)

        let radius: Double = 0.25 // miles
        let distance = desiredLocation.distance(from: userLocation)
        if distance < radius {
       }
    }
}
Lamour
  • 3,002
  • 2
  • 16
  • 28
g. harries
  • 13
  • 4
  • yes the code that calculate distance will go inside IBAction. And you can get the users current location from _manager.location_ – kathayatnk Jun 16 '17 at 17:54
  • so if i use manager.location is the " let userLocation = locations.last! as CLLocation " necessary for my code? and could you copy and paste my code to show me, i'd really appreciate it. thank you! – g. harries Jun 16 '17 at 18:44
  • just startLocationUpdates and then manager.location will have the latest retrieved location. No need for this "let userLocation = locations.last! as CLLocation" See my answer for the IBAction – kathayatnk Jun 16 '17 at 18:54

1 Answers1

0

Something like this

@IBAction func getPoints(_ sender: UIButton) {
    //since this can be nil we have to check if there is any currently retrieved location
    if let currentUserLocation = manager.location {

        //location to check with
        let desiredLocation = CLLocation(latitude: 50.000000, longitude: -50.000000)
        let radius: Double = 0.25 // miles
        let distance = desiredLocation.distance(from: currentUserLocation)
        if distance < radius {
            //do things
        }
    }
}
kathayatnk
  • 975
  • 1
  • 7
  • 9