我正在使用UIViewController将位置传递给另一个具有MapViewprepareForSegue。我称这个为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始终返回true,并以一个岛为中心,并向该奇怪的位置添加注释。

最佳答案

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

 var receivedLocation : CLLocation! = nil

这样,无论是有人设置还是没有设置。如果没有,则为零,您可以测试一下:
if receivedLocation != nil {
    // okay, it's a real location!
}

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

08-26 03:21