2017-06-16 46 views
1

我想要的是,當用戶單擊按鈕時,我希望代碼檢查它們是否在位置附近然後他們拿分,我只是不能確定在哪裏把這些信息當用戶點擊一個按鈕時,他們在靠近某個位置時獲得x點(SWIFT)

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

是該計算距離的代碼裏面去IBAction爲。你可以從_manager.location_ – kathayatnk

+0

獲得用戶當前的位置,所以如果我使用manager.location是我的代碼所需的「let userLocation = locations.last!as CLLocation」?你可以複製並粘貼我的代碼給我看,我真的很感激它。謝謝! –

+0

只是startLocationUpdates,然後manager.location將具有最新的檢索位置。沒有這個需要「讓userLocation = locations.last!作爲CLLocation」 查看我對IBAction的回答 – kathayatnk

回答

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 
     } 
    } 
} 
+0

感謝您澄清,這現在更有意義 –

相關問題