我想取出代表中获取的坐标

时间:2019-03-24 10:21:44

标签: swift core-location

我编写了一个程序,该程序使用LocationManagerDelegate在当前位置更改时在调试区域中显示坐标。检索坐标时出错

不能在属性初始化程序中使用实例成员“ locationManager”;属性初始化程序在“自我”可用之前运行

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)")
}

}

测试(功能) 输出

let myLocation = locationManager ()

更改为

let myLocation = locationManager

1 个答案:

答案 0 :(得分:1)

您的代码包含一些错误。

发生错误是因为您不能在类的顶层执行受影响的行。


首先,您不得更改委托方法的签名。此 custom 委托方法

public static void main(String []args){
    byte b = 6;
    b=b+8;
    //b+=8;
    System.out.println(b);
    b+=7;
    System.out.println(b);
}

从不被呼叫。

此外,为什么您应该将返回类型声明为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)
    }