我是swift的新手,我正在尝试获得一个显示经度和latitutde的基本程序。
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var latLabel: UILabel!
@IBOutlet weak var longLabel: UILabel!
@IBOutlet weak var addLabel: UILabel!
var lm = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
lm = CLLocationManager()
}
@IBAction func getCurrentLocation(_ sender: AnyObject) {
lm.delegate = self
lm.desiredAccuracy = kCLLocationAccuracyBest
lm.startUpdatingLocation()
print("loc")
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print ("error")
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print ("location")
let length = locations.count
let curLoc = locations[length-0]
latLabel.text = String(curLoc.coordinate.latitude)
print ("loccation")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
答案 0 :(得分:3)
你错过了两件事。
因此,当您在 viewdidlod 中分配您的位置管理器时,请执行此操作
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
答案 1 :(得分:1)
检查一次你是否添加了以下信息你的plist
Location :
Key : Privacy - Location Always Usage Description
Value : $(PRODUCT_NAME) location use
Key : Privacy - Location When In Use Usage Description
Value : $(PRODUCT_NAME) location use
有关详细信息,请参阅this
答案 2 :(得分:0)
我发现的另一个问题导致不调用位置更新回调,并且没有给出明显的错误消息,它不能是私有函数(当然,一旦您终于注意到它,这就很明显了……) 。我意识到OP并非如此,但是如果您遇到问题,这是结束的一个常见地方,因此它可能会对某人有所帮助。
因此,以下情况将导致在未给出任何明显的错误指示(如使应用程序崩溃等)的情况下不调用该函数:
private func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print ("location")
let length = locations.count
let curLoc = locations[length-0]
latLabel.text = String(curLoc.coordinate.latitude)
print ("loccation")
}
删除OP的代码中的“ private”关键字,即可对其进行调用。