我编写了一个程序,使用LocationManagerDelegate在当前位置发生变化时显示调试区域中的坐标。检索坐标时出错
不能在属性初始值设定项中使用实例成员'locationManager';属性初始化程序在'self'可用之前运行
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate{
var locationManager: CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
setUpLocationManager()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setUpLocationManager() {
locationManager = CLLocationManager()
guard let locationManager = locationManager else {return}
locationManager.requestWhenInUseAuthorization()
let status = CLLocationManager.authorizationStatus()
if status == .authorizedWhenInUse {
locationManager.delegate = self
locationManager.distanceFilter = 10
locationManager.startUpdatingLocation()
printLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) ->Optional<Any> {
let location = locations.first
let latitude = location?.coordinate.latitude
let longitude = location?.coordinate.longitude
let latlong = [latitude, longitude]
return latlong
}
let myLocation = locationManager()
func printLocation() {
print("test\(myLocation)")
}
}
输出test(Function)
let myLocation = locationManager ()
当你改为
let myLocation = locationManager
您的代码包含一些错误。
发生此错误是因为您无法在类的顶级执行受影响的行。
首先,您不得更改委托方法的签名。这个自定义委托方法
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) ->Optional<Any> { ...
永远不会被召唤。
除此之外,为什么你将返回类型声明为Any?
虽然它应该是[CLLocationCoordinate2D]
?
var locationManager: CLLocationManager!
同
let locationManager = CLLocationManager()
setUpLocationManager()
删除行
locationManager = CLLocationManager()
guard let locationManager = locationManager else {return} // this line is completely pointless anyway
printLocation()
didUpdateLocations
定期和异步调用。在方法内打印结果
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.first else { return }
let latitude = location.coordinate.latitude
let longitude = location.coordinate.longitude
let latlong = [latitude, longitude]
print("test", latlong)
}
let myLocation = locationManager()
func printLocation() {
print("test\(myLocation)")
}