2017-05-14 27 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