2017-05-14 87 views
0

我一直在學習使用swift來製作應用程序,並想製作一個基本的應用程序來告訴你你的速度。但是我無法弄清楚如何讓它更新速度,目前它只給我初始速度,並且從不更新當前速度的標籤。下面是代碼我不得不遠:我怎樣才能讓Swift不斷更新速度

@IBOutlet var speedLabel: UILabel! 
@IBOutlet var countLabel: UILabel! 

let locationManager = CLLocationManager() 
var speed: CLLocationSpeed = CLLocationSpeed() 

override func viewDidLoad() { 

    super.viewDidLoad() 

    locationManager.delegate = self 
    locationManager.desiredAccuracy = kCLLocationAccuracyBest 
    locationManager.startUpdatingLocation() 

    locationManager.startUpdatingLocation() 
    speed = locationManager.location!.speed 

    if speed < 0 { 
     speedLabel.text = "No movement registered" 
    } 
    else { 
     speedLabel.text = "\(speed)" 
    } 


} 

回答

0

使用委託的方法https://developer.apple.com/reference/corelocation/cllocationmanagerdelegate

func locationManager(_ manager: CLLocationManager, 
     didUpdateLocations locations: [CLLocation]) { 

     guard let speed = manager.location?.speed else { return } 
     speedLabel.text = speed < 0 ? "No movement registered" : "\(speed)" 
} 

而且你調用此兩次locationManager.startUpdatingLocation(),這樣你就可以刪除一個呼叫

+0

謝謝!工作! – TomEcho