我尝试将 CoreLocation 与 Swift 结合使用来跟踪用户的位置:
(您可以在下面找到可能的 ViewController.swift 文件的代码。)
但代码似乎并没有像我预期的那样工作,因为我每次启动应用程序时仍然遇到相同的错误:
我确定这就是我无法从应打印出当前位置的 locationManager()
函数获得结果的问题。
它说 “无法将类型‘ViewController’的值分配给类型‘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
一样直接在类声明中执行此操作,也可以在 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)
}
}
}
关于ios - 如何以正确的方式跟踪 set locationManager.delegate?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48487164/