如何在applicationDidEnterBackground中从ViewController停止locationManager更新

时间:2015-03-30 06:08:01

标签: ios xcode swift

我需要在applicationDidEnterBackground时从AppDelegate停止locationUpdates,并在ViewController中的applicationDidBecomeActive时启动startUpdatingLocation,这里是我的代码..

如果我的locationManager在ViewController中,怎么做呢。

import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate

var seenError : Bool = false
var locationFixAchieved : Bool = false
var locationStatus : NSString = "Not Started"

var locationManager: CLLocationManager!

override func viewDidLoad() {
    super.viewDidLoad()
}

  func initLocationManager() {
   seenError = false
   locationFixAchieved = false
    locationManager = CLLocationManager()
   locationManager.delegate = self
   locationManager.locationServicesEnabled
   locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestAlwaysAuthorization()
}

  func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
    locationManager.stopUpdatingLocation()
    if (error) {
        if (seenError == false) {
            seenError = true
           print(error)
        }
    }
}

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: AnyObject[]!) {
    if (locationFixAchieved == false) {
        locationFixAchieved = true
        var locationArray = locations as NSArray
        var locationObj = locationArray.lastObject as CLLocation
        var coord = locationObj.coordinate

        println(coord.latitude)
        println(coord.longitude)
    }
}

 func locationManager(manager: CLLocationManager!,
    didChangeAuthorizationStatus status: CLAuthorizationStatus) {
        var shouldIAllow = false

        switch status {
        case CLAuthorizationStatus.Restricted:
            locationStatus = "Restricted Access to location"
        case CLAuthorizationStatus.Denied:
            locationStatus = "User denied access to location"
        case CLAuthorizationStatus.NotDetermined:
            locationStatus = "Status not determined"
        default:
            locationStatus = "Allowed to location Access"
            shouldIAllow = true
        }
        NSNotificationCenter.defaultCenter().postNotificationName("LabelHasbeenUpdated", object: nil)
        if (shouldIAllow == true) {
            NSLog("Location to Allowed")
            // Start location services
            locationManager.startUpdatingLocation()
        } else {
            NSLog("Denied access: \(locationStatus)")
        }
}

3 个答案:

答案 0 :(得分:4)

NSNotificationCenter是一种在应用程序中发送消息的简单方法。每个需要响应此类消息的类都会注册一个观察者来监听该消息。

<强>的AppDelegate:

func applicationDidEnterBackground(application: UIApplication) {
    // Send a message that informs all listening classes for entering background
    NSNotificationCenter.defaultCenter().postNotification(NSNotification(name: "appEntersBackground", object: nil))
}

func applicationDidBecomeActive(application: UIApplication) {
    // Send a message that informs all listening classes for becoming active again
    NSNotificationCenter.defaultCenter().postNotification(NSNotification(name: "appBecomesActive", object: nil))
}

Swift 4.2

NotificationCenter.default.post(name: Notification.Name("appEntersBackground"), object: nil)

<强>的ViewController

在viewController中,为消息注册观察者:

class ViewController: UIViewController, CLLocationManagerDelegate {
    ...

    override func viewDidLoad() {
        super.viewDidLoad()

        // register observers
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "enterBackground", name: "appEntersBackground", object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "becomeActive", name: "appBecomesActive", object: nil)
    }

    deinit {
        // remove observers
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

    // app enters background
    func enterBackground() {
        self.locationManager.stopUpdatingLocation()
    }

    // app becomes active
    func becomeActive() {
        self.locationManager.startUpdatingLocation()
    }

}

Swift 4.2

    NotificationCenter.default.addObserver(self, selector: #selector(enterBackground), name: Notification.Name("appEntersBackground"), object: nil)

@objc func enterBackground() {
            self.locationManager.stopUpdatingLocation()
        }

请注意,除非您在Info.plist中为后台任务注册了应用,否则locationmanager会停止在后台更新位置。

答案 1 :(得分:0)

您可以从startUpdatingLocationapplicationDidBecomeActive点击来自stopUpdatingLocation的通知applicationDidEnterBackground。然后,您可以在视图控制器中收听这些通知以管理locationManager

答案 2 :(得分:0)

您可以使用此代码 -

func applicationDidEnterBackground(application: UIApplication) {

    self.locationManager.stopUpdatingLocation() 
}

func applicationDidBecomeActive(application: UIApplication) {

    self.locationManager.startUpdatingLocation()
}

还有一个建议,您可以检查initLocationManager方法 -

if (self.locationManager.respondsToSelector(Selector("requestAlwaysAuthorization"))) {
        self.locationManager.requestAlwaysAuthorization()
    }