【发布时间】:2015-01-05 12:21:16
【问题描述】:
我一直在尝试使用以下代码从 CoreLocation 框架中获取的 CLLocation 获取高度:
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
/*
Note: This needs to be added to the info.plist file for this to work:
<key>NSLocationUsageDescription</key> <string>Your message</string> <key>NSLocationAlwaysUsageDescription</key> <string>Your message</string> <key>NSLocationWhenInUsageDescription</key>
<string>Your message</string>
*/
@IBOutlet weak var gpsResult: UILabel!
@IBOutlet weak var altitudeLabel: UILabel!
var manager:CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
manager = CLLocationManager()
manager.delegate = self
manager.distanceFilter = kCLDistanceFilterNone
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestAlwaysAuthorization()
manager.startUpdatingLocation()
}
func locationManager(manager:CLLocationManager!, didUpdateLocations myLocations:CLLocation) {
if manager != nil {
var alt:CLLocationDistance = myLocations.altitude
gpsResult.text = "locations = \(myLocations)"
altitudeLabel.text = "GPS Altitude: \(Double(alt))"
// manager.stopUpdatingLocation()
}
}
}
因此,如果我只请求位置,我可以获得 gpsResult.text 值并且它可以正常工作,但是当我尝试访问高度时出现错误:
'NSInvalidArgumentException', reason: '-[__NSArrayM altitude]: unrecognized selector sent to instance 0x17404dcb0'
事情是根据apple's reference,选择器应该存在。 我浏览了这里的帖子和网络,并尝试了他们的代码,但都失败了。
有人知道发生了什么吗?
谢谢。
【问题讨论】:
-
您正在对数组运行它。 MyLocations 是一个数组而不是 CLLocation。
-
@Fogmeister 是正确的。 didUpdateLocations 委托方法传递一个 CLLocation 对象数组(因此 myLocations 参数类型应该是
[AnyObject]!)。通过将其“声明”为单个 CLLocation,它不会自动变成单个 CLLocation——它仍然是一个 CLLocation 数组。
标签: ios swift gps cllocation