Swift:从后台返回时位置未更新 [英] Swift: location not being updated when returned from background

查看:88
本文介绍了Swift:从后台返回时位置未更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Swift应用程序,当我从后台返回该应用程序时,我试图更新该位置,但是从后台返回时,它似乎不起作用。

I have a Swift app that I am trying to update the location when the app is returned from the background, but it doesn't seem to work when returned from the background.

启动该应用程序后,我将获得正确的位置。获取位置后,我调用stopUpdatingLocation(),所以不再继续获取位置:
locationManager.stopUpdatingLocation()

On launch of the app, I'll get the location just fine. After getting the location I call stopUpdatingLocation() so I don't continue to get the location: locationManager.stopUpdatingLocation()

然后在AppDelegate中。我再次迅速启动UpUpdatingLocation:

Then, in my AppDelegate.swift I startUpdatingLocation again:

func applicationWillEnterForeground(application: UIApplication) {

    ViewController().locationManager.startUpdatingLocation()
}

到目前为止,这是我的代码:

This is my code so far:

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()

}

}

但是,每当我后台应用程序(单击主页),然后返回到应用程序,位置未更新。知道我在这里可能做错了什么吗?

However, whenever I background the app (click home), and then return to the app the location isn't updated. Any idea what I might be doing wrong here?

推荐答案

applicationWillEnterForeground ,代码正在创建一个从未显示过的 ViewController 的新本地实例,尚未创建 locationManager

In applicationWillEnterForeground, the code is creating a new, local instance of ViewController that is never displayed, does not yet have a locationManager created and so has no effect.

它不是指已经存在并显示的 ViewController 实例。具有最初启动的 locationManager 实例。

It is not referring to the ViewController instance that already exists and is displayed (and has the locationManager instance that was originally started).

相反,它应该获得对现有实例的引用。假设 ViewController 是根视图控制器,则可以执行以下操作:

Instead, it should get a reference to the existing instance. Assuming ViewController is the root view controller, you could do:

func applicationWillEnterForeground(application: UIApplication) {

    if let rvc = window?.rootViewController as? ViewController {
        rvc.locationManager.startUpdatingLocation()
    }

}



但是,最好让 ViewController 类本身管理自己的行为。这样,应用程序委托就不必查找对视图控制器实例的引用,也不必直接访问视图控制器的内部状态,并且 ViewController 变得更加自我。


However, it might be better practice to let the ViewController class itself manage its own behavior. This way, the app delegate doesn't have to find a reference to the view controller's instance and it doesn't directly access the view controller's internal state and ViewController becomes more self-contained.

除了应用程序委托方法 applicationWillEnterForeground ,还可以使用 UIApplicationWillEnterForegroundNotification 通知。

In addition to the app delegate method applicationWillEnterForeground, it's possible to monitor these events from anywhere using the UIApplicationWillEnterForegroundNotification notification.

ViewController 中,您可以注册和在(例如) viewWillAppear viewWillDisappear 中取消注册通知。注册时,您指示要调用该事件的方法,并且所有内容都在 ViewController 内部处理(以及 applicationWillEnterForeground 中的代码可以删除)。

In ViewController, you can register and unregister for the notification in (for example) viewWillAppear and viewWillDisappear. When registering, you indicate which method to call for the event and everything is handled inside ViewController (and the code in applicationWillEnterForeground can be removed).

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()
}

这篇关于Swift:从后台返回时位置未更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆