如何以正确的方式跟踪 set locationManager.delegate?

How to track set locationManager.delegate the right way?

我尝试将 CoreLocation 与 Swift 结合使用来跟踪用户的位置:
(下面你可以找到ViewController.swift文件的代码。)

但是代码似乎并没有像我预期的那样工作,因为我每次启动应用程序时仍然遇到相同的错误

我确定这就是为什么我无法从应该打印出当前位置的 locationManager() 函数获得结果的问题。

它说 "Cannot assign value of type 'ViewController' to type 'CLLocationManagerDelegate?'"

import UIKit
import CoreLocation 

class ViewController: UIViewController, WKUIDelegate {
  override func viewDidLoad() {
    super.viewDidLoad()
    if CLLocationManager.locationServicesEnabled() {
        print("CLLocationManager is available")
        locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers
        locationManager.delegate = self
        locationManager.startUpdatingLocation()
    }
  }

  let locationManager = CLLocationManager()

  func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let location = locations.first {
        print(location.coordinate)
    }
  }
}

现在有人知道如何解决这个问题吗? - 任何帮助将不胜感激,提前一百万表示感谢。

您只需声明符合 CLLocationManagerDelegate。您可以像使用 WKUIDelegate 一样直接在 class 声明中执行此操作,也可以在 ViewController.

的扩展中执行此操作
class ViewController: UIViewController, WKUIDelegate, CLLocationManagerDelegate {
    override func viewDidLoad() {
        super.viewDidLoad()
        if CLLocationManager.locationServicesEnabled() {
            print("CLLocationManager is available")
            locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers
            locationManager.delegate = self
            locationManager.startUpdatingLocation()
        }
    }

    let locationManager = CLLocationManager()

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let location = locations.first {
            print(location.coordinate)
        }
    }
}

扩展名:

class ViewController: UIViewController, WKUIDelegate {
    let locationManager = CLLocationManager()
    override func viewDidLoad() {
        super.viewDidLoad()
        if CLLocationManager.locationServicesEnabled() {
            print("CLLocationManager is available")
            locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers
            locationManager.delegate = self
            locationManager.startUpdatingLocation()
        }
    }
}

extension ViewController: CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let location = locations.first {
            print(location.coordinate)
        }
    }
}