CLLocationManager只能运行一次

时间:2017-07-06 17:36:58

标签: swift macos

我是swift的新手 - 目前,当我第一次通过setupLocationManager()呼叫override func awakeFromNib()时,我的当前位置仅在控制台中输出一次。当我单击一个方法为locationManager.startUpdatingLocation()的按钮时,我希望它通过调用updateLocation()来输出我的新位置,它会输出错误。有任何解决这个问题的方法吗?感谢所有帮助。

import Cocoa
import CoreLocation

class StatusMenuController: NSObject, CLLocationManagerDelegate {

@IBOutlet weak var statusMenu: NSMenu!
let statusItem = NSStatusBar.system().statusItem(withLength: NSVariableStatusItemLength)
var locationManager:CLLocationManager!
var currentLocation:CLLocation?

@IBAction func quitClicked(_ sender: NSMenuItem) {
    NSApplication.shared().terminate(self)
}

@IBAction func updateClicked(_ sender: NSMenuItem) {
    updateLocation()
}

func updateLocation() {
    locationManager.startUpdatingLocation()
}

override func awakeFromNib() {
    statusItem.menu = statusMenu
    let icon = NSImage(named: "statusIcon")
    icon?.isTemplate = true
    statusItem.image = icon
    statusItem.menu = statusMenu
    setupLocationManager()
}

func setupLocationManager(){
    locationManager = CLLocationManager()
    locationManager?.delegate = self
    //self.locationManager?.requestAlwaysAuthorization()
    locationManager?.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
    locationManager?.startUpdatingLocation()

}

// Below method will provide you current location.
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    if currentLocation == nil {
        currentLocation = locations.last
        locationManager?.stopMonitoringSignificantLocationChanges()
        let locationValue:CLLocationCoordinate2D = manager.location!.coordinate

        print(locationValue)

        locationManager?.stopUpdatingLocation()
    }
}

// Below Method will print error if not able to update location.
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
    print("Error")
}

}

1 个答案:

答案 0 :(得分:0)

代码中存在if条件,该位置设置一次(if currentLocation == nil)后暂停更新位置。在重新启动经理之前,您必须将currentLocation重置为nil

@IBAction func updateClicked(_ sender: NSMenuItem) {
    currentLocation = nil
    updateLocation()
}