2016-12-05 46 views
2

看看這裏Finding Altitude in Swift 再看看我的代碼核心位置返回0海拔

import CoreLocation 

class ViewController: UIViewController, CLLocationManagerDelegate { 

    @IBOutlet weak var lbl: UILabel! 
    var player: AVAudioPlayer? 

    var locationManager:CLLocationManager = CLLocationManager() 

    var alt: Double? 

    @IBOutlet weak var coor: UILabel! 

    func locationManager(manager: CLLocationManager!, didUpdateToLocation newLocation: CLLocation!, fromLocation oldLocation: CLLocation!) { 
     alt = newLocation.altitude 
     var altitude = locationManager.location?.altitude 
     print("\(altitude)") 
     manager.stopUpdatingLocation() 
    } 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 
     self.locationManager = CLLocationManager() 
     locationManager.requestWhenInUseAuthorization() 
     self.locationManager.delegate = self 
     self.locationManager.distanceFilter = kCLDistanceFilterNone 
     self.locationManager.desiredAccuracy = kCLLocationAccuracyBest 
     self.locationManager.startUpdatingLocation() 
    } 

    @IBAction func getCoor(_ sender: Any) { 
     var altitude = locationManager.location?.altitude 
     coor.text = "\(altitude)" 
    } 
} 

爲什麼它不顯示我的實際高度,而不是總是顯示0.0≦

+0

你的高度是多少?它返回什麼經緯度?地點是否爲零?實際上是否有位置?你在模擬器上的設備上運行嗎? – Fogmeister

+0

它快3嗎? –

+0

是的,我必須在swift中編寫代碼3 –

回答

0

這種代碼是註定要失敗:

func locationManager(manager: CLLocationManager!, didUpdateToLocation newLocation: CLLocation!, fromLocation oldLocation: CLLocation!) { 
    // ... 
    manager.stopUpdatingLocation() 
} 

在已經開始的位置經理startUpdatingLocation,你停在第一個調用didUpdateLocation位置管理。但第一個電話總是虛假的,甚至接下來的十幾個電話都可能只是熱身,因爲硬件獲得了修復。

如果您的問題是「我在哪裏」,請使用requestLocation而不是startUpdatingLocation。它只調用didUpdateLocation一次,只有當它實際上確實有有足夠好的位置(這可能需要一些時間)。

最後,請注意,您的代碼在Swift 3中不正確。locationManager(manager:...)從不調用Read the docs來學習正確的簽名。

0

您正在將newlocation.altitude存儲到「alt」變量中,但正在打印「高度」。

嘗試:print("\(alt)")