2015-02-23 42 views
1

我有一個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() 

} 

} 

但是,每當我背景的應用程序(單擊家庭),然後返回到應用程序的位置不更新。任何想法,我可能在這裏做錯了嗎?

回答

2

applicationWillEnterForeground中,代碼創建了一個新的本地實例ViewController,它從不顯示,還沒有創建locationManager,因此沒有任何作用。

它不是指已存在並顯示(並且具有最初啓動的locationManager實例)的ViewController實例。

相反,它應該獲得對現有實例的引用。假設ViewController是根視圖控制器,你可以這樣做:

func applicationWillEnterForeground(application: UIApplication) { 

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

} 


但是,它可能是更好的做法讓 ViewController類本身管理自己的行爲。這樣,應用程序委託不必查找對視圖控制器實例的引用,它不直接訪問視圖控制器的內部狀態,並且變得更加獨立。

除了應用程序委託方法applicationWillEnterForeground之外,還可以使用UIApplicationWillEnterForegroundNotification通知從任何地方監視這些事件。

ViewController中,您可以註冊和取消註冊(例如)viewWillAppearviewWillDisappear中的通知。在註冊時,您指出要調用事件的方法,並且所有內容都在ViewController內處理(並且applicationWillEnterForeground中的代碼可以刪除)。

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

謝謝安娜,非常有道理,不知道我錯過了它是如何創建ViewController的新實例,而不是使用現有的。 – 2015-02-23 15:24:21