我有一個Swift應用程序,我試圖更新位置,當應用程序從後臺返回時,但它似乎不工作時,從後臺返回。Swift:從後臺返回位置不更新
在應用程序啓動時,我會得到位置很好。再次 locationManager.stopUpdatingLocation()
然後,在我的AppDelegate.swift我startUpdatingLocation:讓我叫stopUpdatingLocation(位置)之後,所以我沒有繼續得到位置
func applicationWillEnterForeground(application: UIApplication) {
ViewController().locationManager.startUpdatingLocation()
}
這是我的代碼到目前爲止:
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
println("Error while updating location " + error.localizedDescription)
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
var userLocation:CLLocation = locations[0] as CLLocation
println("\(userLocation.coordinate.latitude),\(userLocation.coordinate.longitude)")
locationManager.stopUpdatingLocation()
}
}
但是,每當我背景的應用程序(單擊家庭),然後返回到應用程序的位置不更新。任何想法,我可能在這裏做錯了嗎?
謝謝安娜,非常有道理,不知道我錯過了它是如何創建ViewController的新實例,而不是使用現有的。 – 2015-02-23 15:24:21