2017-07-06 8 views
0

作品 - 私が最初override func awakeFromNib()を通じてinitのsetupLocationManager()を呼び出すと、現在、私の現在の場所は、かつてコンソールでのみ出力されます。私はこの方法updateLocation()でボタンをクリックしたときにlocationManager.startUpdatingLocation()呼び出すことによって、出力私の新しい場所にそれをしたい場合は、エラーを出力します。これを修正する方法はありますか?すべての助けに感謝します。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条件があります。あなたは、マネージャを再起動する前nilcurrentLocationをリセットする必要があります。

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

すごいああ!ありがとう!もう一つの問題は、プロセスに来ている - 時々私はそれが動作を呼び出す際に、他の回のエラー - これは、ランダムに出てくるようです。おそらくインターネットの問題?さらに、成功すると、その場所を2回(まれに)4回印刷します。ワンボタンで複数の印刷をクリック。アプリがinitで最初に実行されるときには、それは一度しか印刷されません。可能な解決策はありますか?とても有難い! – skywang329

+0

私はCoreLocation – vadian

+0

ネヴァーマインドとその慣れていないよ:Pはとにかく感謝:)解決策を見つけました! – skywang329