gpt4 book ai didi

swift - locationmanager不更新坐标

转载 作者:行者123 更新时间:2023-11-30 13:06:33 25 4
gpt4 key购买 nike

我只是在 Xcode 上使用 Swift 3 尝试一个 map 示例。我设法将 map View 放在屏幕上并在模拟器上运行该项目。当我按预期更改模拟位置时,我可以看到坐标发生移动。

但是我无法打印当前坐标。我确实在屏幕上放置了一个按钮,这样当单击它时,位置管理器给出的坐标应该会打印在 Xcode 终端中。我在下面包含了我的代码,按钮操作 showCooperatives 应该打印当前坐标。

import UIKit
import MapKit

class ViewController: UIViewController, CLLocationManagerDelegate {

@IBOutlet weak var mapView: MKMapView!

let locationManager = CLLocationManager()


override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}

@IBOutlet weak var myLattitude: UILabel! // These are the labels that will show the coordinate on the screen when pressed.
@IBOutlet weak var myLongitude: UILabel!

@IBAction func showCoordinates(_ sender: AnyObject) {

let myCoordinate = locationManager.location?.coordinate
print(myCoordinate) // This does not work as expected
}


func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
guard status == .authorizedWhenInUse else {
print("Location not enabled")
return
}

print("Location allowed.")
mapView.showsUserLocation = true
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

}

当我在模拟器中运行它并更改模拟坐标时, map 中的蓝点移动得很好,但显示坐标按钮仅打印第一个位置。即使位置发生变化,它也会打印第一个位置。我怎样才能使其正常工作?

最佳答案

ViewControllerfunc locationManager(_ manager: CLLocationManager, didUpdateLocationslocations: [CLLocation]) 调用 showCooperatives(_ sender: AnyObject) 函数

像这样:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
showCoordinates(self)
}

或者,您可以直接在 didUpdateLocations 回调中输入它,如下所示:

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

但是委托(delegate)是一种更好的方法,因为如果您想更改格式,或者做一些额外的工作而不是简单地打印坐标,您只需更改一个函数。如果您不使用委托(delegate),您最终会得到两个独立的函数,您必须分别维护和更新它们,即使它们执行相同的操作。

关于swift - locationmanager不更新坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39293039/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com