在Swift中,当我按下按钮时,如何将用户的位置存储在变量中?

时间:2015-05-09 19:41:17

标签: ios swift core-location

在主UIViewController中,我想在按下UIButton时将用户的坐标存储在变量中。此变量将在具有UIViewController的其他MapView中使用。

我尝试设置locationManager(),但我无法使用该按钮。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:3)

以下是可以帮助您的代码:

var location: CLLocation! //to store location
lazy var locationManager: CLLocationManager = {
    let _locationManager = CLLocationManager()
    _locationManager.requestWhenInUseAuthorization()
    // adjsut _locationManager
    return _locationManager
}()

override func viewDidLoad() {
    super.viewDidLoad()
    locationManager.startUpdatingLocation()
}

@IBAction func buttonDidClick(sender: AnyObject) { //event handler
    location = locationManager.location //set current location
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "MyViewControllerSegue" { //before showing controller
        let dvc = segue.destinationViewController as! ViewController
        dvc.location = location //set the current location
    }
}