ios - 如何在 applicationDidEnterBackground 中停止来自 ViewController 的 locationManagerUpdates

标签 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)")
        }
}

最佳答案

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)

View Controller

在您的 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()
        }

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

关于ios - 如何在 applicationDidEnterBackground 中停止来自 ViewController 的 locationManagerUpdates,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29339408/

相关文章:

iphone - 无法从 NSXMLParser 解码 UTF8 字符

swift - 如何制作隐藏在 Swift 4 中的默认 GSMapView InfoWindowOfMarker UIView 框架?

Swift 结构属性与结构本身的类型相同。递归?

ios - 我怎样才能让 UIPickerview 自动更新 UILabel

iPhone 实时消息

ios - 如何将 Date(1440156888750-0700) 这样的日期转换为 Swift 可以处理的东西?

objective-c - 从索引处的 NSMutableDictionary 中删除对象

ios - 在 Swift 的 UIKit 文档中查找有关构造函数的信息

ios - 通过segue和sqlite传递数据

ios - 如何在 itunesconnect 上查看我的 ios 应用程序版本历史详细信息