gpt4 book ai didi

ios - 在 Swift 中,我可以检测 CLLocation 是否有效吗?

转载 作者:搜寻专家 更新时间:2023-10-31 22:15:46 24 4
gpt4 key购买 nike

我正在将一个位置传递给另一个 UIViewController,它有一个使用 prepareForSegueMapView。我称之为 receivedLocation。 map 以经过的位置为中心。如果用户在没有先发送位置的情况下单击按钮将他们带到 map ,这不会失败吗?

我如何测试以查看 receivedLocation 是否确实包含数据,以便在 map 为空时将 map 设置为以其他内容为中心?

是否会创建一个 bool 变量,最初将其设置为 false,但在传递位置并测试时将其设置为 true 能否如我所愿?

我看到一个名为 CLLocationCoordinateIsValid 的东西可用,但它的参数是一个 2DCoordinate,我遇到了同样的问题,即测试是否 receivedLocation

我在这方面还很陌生,已经尝试寻找答案但找不到合适的答案。谢谢!

import UIKit
import MapKit
import CoreLocation

class mapViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {

@IBOutlet var map: MKMapView!
@IBOutlet var notes: UITextView!

var receivedLocation = CLLocation()
var annotation = MKPointAnnotation()
var currentManager:CLLocationManager!

var latitute:CLLocationDegrees = CLLocationDegrees()
var longitude:CLLocationDegrees = CLLocationDegrees()

override func viewDidLoad() {
super.viewDidLoad()

map.layer.cornerRadius = 12.0
notes.layer.cornerRadius = 12.0

currentManager = CLLocationManager()
currentManager.delegate = self
currentManager.desiredAccuracy = kCLLocationAccuracyBest
currentManager.startUpdatingLocation()

if CLLocationCoordinate2DIsValid(receivedLocation.coordinate) {

latitute = receivedLocation.coordinate.latitude
longitude = receivedLocation.coordinate.longitude
annotation.coordinate.latitude = receivedLocation.coordinate.latitude
annotation.coordinate.longitude = receivedLocation.coordinate.longitude
map.addAnnotation(annotation)

} else {

latitute = currentManager.location.coordinate.latitude
longitude = currentManager.location.coordinate.longitude
}

var latDelta: CLLocationDegrees = 0.01
var lonDelta: CLLocationDegrees = 0.01
var span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta)
var location : CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitute, longitude)
var region: MKCoordinateRegion = MKCoordinateRegionMake(location, span)
map.setRegion(region, animated: false)

}

到目前为止,这对我不起作用。 CLLocationCoordinate2DIsValid 始终返回 true 并以岛屿为中心,并向那个奇怪的地方添加注释。

最佳答案

首先,不要不必要地将无用的CLLocation() 放入receivedLocation 中。将 receivedLocation 声明为隐式解包可选:

 var receivedLocation : CLLocation! = nil

这样,要么有人设置了它,要么没有。如果没有,则为 nil,您可以测试一下:

if receivedLocation != nil {
// okay, it's a real location!
}

其次,您的 else 永远不会工作,因为传感器需要时间预热和定位 - 事实上,它们可能永远定位不到。所以我可以很好地保证,在 receivedLocation nil 的情况下,currentManager.location 也不会有任何用处。 (有关如何使用位置管理器获取单个位置值的说明和示例代码的指针,请参阅 my answer here。)

关于ios - 在 Swift 中,我可以检测 CLLocation 是否有效吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30159613/

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