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

Cod*_*cas 3 core-location mapkit ios swift

我正在将一个位置传递给另一个UIViewControllerMapView使用的位置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)

    }
Run Code Online (Sandbox Code Playgroud)

到目前为止,这对我不起作用.CLLocationCoordinate2DIsValid始终返回true并以岛屿为中心,并为该奇怪点添加注释.

mat*_*att 5

首先,不要把一个无用的东西CLLocation()放进去receivedLocation.声明receivedLocation为隐式解包的可选:

 var receivedLocation : CLLocation! = nil
Run Code Online (Sandbox Code Playgroud)

这样,无论是有人设置了还是没有设置它.如果他们没有,那就是零,你可以测试:

if receivedLocation != nil {
    // okay, it's a real location!
}
Run Code Online (Sandbox Code Playgroud)

其次,你else永远不会工作,因为传感器需要时间来预热并获得一个位置 - 事实上,它们可能永远不会得到一个.因此,我可以很好保证的情况下receivedLocation 零,currentManager.location不会有任何兼用.(有关如何使用位置管理器获取单个位置值的解释和指向示例代码的指针,请参阅此处答案.)