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

In Swift, can I detect if a CLLocation is valid or not?

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

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

是否会创建一个布尔变量,最初将其设置为 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 始终 returns true 并以岛屿为中心,并向那个奇怪的地方添加注释。

首先,不要把无用的CLLocation()塞进receivedLocation。将 receivedLocation 声明为隐式解包 可选:

 var receivedLocation : CLLocation! = nil

那样的话,要么有人设置了,要么没有。如果没有,则为零,您可以测试一下:

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

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