当用户点击按钮时,当他们靠近某个位置时,他们会得到x分(SWIFT)

时间:2017-06-16 17:45:05

标签: swift xcode location cllocationmanager reward-system

我的目标是,当用户点击按钮时,我希望代码检查他们是否在该位置附近,然后他们获得积分,我只是不确定在哪里放置该信息

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 {
       }
    }
}

1 个答案:

答案 0 :(得分:0)

像这样的东西

@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
        }
    }
}