2017-07-06 114 views
0

我是新來的swift--目前,我的當前位置只在控制檯中輸出一次,當我通過override func awakeFromNib()在init初次調用setupLocationManager()時。當我想通過調用locationManager.startUpdatingLocation()來輸出我的新位置時,當我用方法updateLocation()單擊一個按鈕時,它會輸出一個錯誤。有任何解決這個問題的方法嗎?所有的幫助表示讚賞。CLLocationManager只能運行一次

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

} 

回答

0

有一個在位置設置一次(if currentLocation == nil)之後中止對更新位置代碼的if條件。在重新啓動管理器之前,必須重置currentLocationnil

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

哦哇!謝謝!在這個過程中出現了另一個問題 - 有時我把它稱作是有效的,有時候它是一個錯誤 - 這似乎是隨機出現的。也許是互聯網問題?此外,當它成功時,它將打印兩次或(很少)四次的位置。在一個按鈕上點擊多次打印;但是當應用程序第一次運行時,它只會打印一次。任何可能的解非常感激! – skywang329

+0

我不是那麼熟悉CoreLocation – vadian

+0

Nevermind:P找到了解決方案:)謝謝反正!!! – skywang329