Swift:从后台返回时未更新位置
我有一个Swift应用程序,当应用程序从后台返回时,我正在尝试更新位置,但从后台返回时它似乎不起作用 在应用程序启动时,我会找到合适的位置。获取位置后,我调用StopUpdateLocation(),因此我不会继续获取位置: locationManager.StopUpdatengLocation() 然后,在我的AppDelegate.swift中,我再次启动DatingLocation:Swift:从后台返回时未更新位置,swift,core-location,Swift,Core Location,我有一个Swift应用程序,当应用程序从后台返回时,我正在尝试更新位置,但从后台返回时它似乎不起作用 在应用程序启动时,我会找到合适的位置。获取位置后,我调用StopUpdateLocation(),因此我不会继续获取位置: locationManager.StopUpdatengLocation() 然后,在我的AppDelegate.swift中,我再次启动DatingLocation: func applicationWillEnterForeground(application: UIA
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
实例(并且具有最初启动的locationManager
实例)
相反,它应该获得对现有实例的引用。假设ViewController
是根视图控制器,则可以执行以下操作:
func applicationWillEnterForeground(application: UIApplication) {
if let rvc = window?.rootViewController as? ViewController {
rvc.locationManager.startUpdatingLocation()
}
}
但是,最好让
ViewController
类自己管理自己的行为。这样,应用程序委托就不必找到对视图控制器实例的引用,也不必直接访问视图控制器的内部状态,ViewController
变得更加独立
除了应用程序委派方法applicationWillEnterForeground
,还可以使用UIApplicationWillEnterForegroundNotification
通知从任何位置监视这些事件
在ViewController
中,您可以在(例如)viewwillbeen
和viewwillbeside
中注册和取消注册通知。注册时,您可以指定调用事件的方法,并且在ViewController
中处理所有内容(并且应用程序中的代码可以删除)
谢谢Anna,这很有意义,我不知道我怎么会错过它是在创建一个新的ViewController实例,而不是使用现有的。
override func viewWillAppear(animated: Bool) {
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: "willEnterForegound",
name: UIApplicationWillEnterForegroundNotification,
object: nil)
}
override func viewWillDisappear(animated: Bool) {
NSNotificationCenter.defaultCenter().removeObserver(
self,
name: UIApplicationWillEnterForegroundNotification,
object: nil)
}
func willEnterForegound() {
locationManager.startUpdatingLocation()
}