我的目标是当用户单击按钮时,我希望代码检查他们是否在该位置附近,然后他们获得积分,我只是不确定将这些信息放在哪里
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 {
}
}
}
像这样的东西
@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
}
}
}