2016-07-25 41 views
3

我很難找到設備的高度,我需要在我的應用程序中顯示高度我該怎麼做? 我已經試過了:如何獲得ios 8當前的高度?

var locationManager:CLLocationManager = CLLocationManager() 

override func viewDidLoad() { 

    super.viewDidLoad() 
    self.locationManager = CLLocationManager() 
    locationManager.requestWhenInUseAuthorization() 
    self.locationManager.delegate = self 
    self.locationManager.distanceFilter = kCLDistanceFilterNone 
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest 
    self.locationManager.startUpdatingLocation() 

} 


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

沒有露面....

+1

您是否在'info.plist'中添加了'NSLocationAlwaysUsageDescription'鍵? – WMios

+0

你在你的info.plist中包含了「NSLocationAlwaysUsageDescription'鍵嗎? – AtWork

+0

實際上OP是要求使用授權,所以他需要一個NSLocationInUseDescription,或者任何正在使用的版本。 –

回答

3

其實你是不是調用正確的委託方法,你在呼喚: locationManager(manager: CLLocationManager!, didUpdateToLocation newLocation: CLLocation!, fromLocation oldLocation: CLLocation!)但一會給你想要的東西爲locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])

所以,如果你沒有實現NSLocationWhenInUseUsageDescription鑰匙到您的Info.plist文件,如果該彈出窗口顯示你只需要刪除您的功能,並添加這一項,它應該工作:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 
    guard let lastLocation = locations.last else { 
     NSLog("error no last location") 
     return 
    } 
    let altitude = lastLocation.altitude 
    // Do what you want with your altitude 
} 

我也建議你不要在這個委託函數裏面調用locationManager.stopUpdatingLocation()

希望這會幫助你!

說明:該語法適用於Swift 3.0,但我認爲您只需在Swift 2.2的代理函數中刪除_即可。

+0

它正在工作!它是英尺還是米? –

+0

根據[AppleDocumentation](https://developer.apple.com/library/ios/documentation/CoreLocation/Reference/CLLocation_Class/index.html#//apple_ref/occ/instp/CLLocation/altitude), 'The以米爲單位測量高度。 (只讀)' – Chajmz