Reputation: 3
So, I am trying to get my Location inside a function of my ViewController.swift.
The Code I use works when i try it like this:
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
var manager : CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
manager = CLLocationManager()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyHundredMeters
manager.requestAlwaysAuthorization()
manager.startUpdatingLocation()
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
var locValue : CLLocationCoordinate2D
locValue = manager.location.coordinate
println("Coordinates = \(locValue.longitude) + \(locValue.latitude)")
manager.stopUpdatingLocation()
}
But what I am trying to do is get it while pressing a button which toggles a function:
var manager : CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
manager = CLLocationManager()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyHundredMeters
manager.requestAlwaysAuthorization()
manager.startUpdatingLocation()
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
var locValue: CLLocationCoordinate2D = manager.location.coordinate
println("locations = \(locValue.longitude) \(locValue.latitude)")
manager.stopUpdatingLocation()
}
@IBAction func refresh() {
getWeatherData()
refreshButton.hidden = true
acitivityIndicatorView.hidden = false
acitivityIndicatorView.startAnimating()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func getWeatherData() -> Void {
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [AnyObject]!) {
var locValue: CLLocationCoordinate2D = manager.location.coordinate
println("locations = \(locValue.longitude) \(locValue.latitude)")
manager.stopUpdatingLocation()
While using a breakpoint i realized it gets to func locationManager but it jumps to the end of my getweatherdata() function.
I can't see why it doesn't work.
Upvotes: 0
Views: 285
Reputation: 24572
What you are doing is not possible. Inly thing you can do is call manager.startUpdatingLocation()
inside refresh()
and wait till didUpdateLocations
get called with the updated location data.
@IBAction func refresh() {
manager.startUpdatingLocation()
refreshButton.hidden = true
acitivityIndicatorView.hidden = false
activityIndicatorView.hidesWhenStopped = true
acitivityIndicatorView.startAnimating()
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
var locValue: CLLocationCoordinate2D = manager.location.coordinate
println("locations = \(locValue.longitude) \(locValue.latitude)")
manager.stopUpdatingLocation()
refreshButton.hidden = false
acitivityIndicatorView.stopAnimating()
}
Upvotes: 1