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

时间:2015-05-11 04:19:54

标签: ios swift mapkit core-location

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

1 个答案:

答案 0 :(得分:5)

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

 var receivedLocation : CLLocation! = nil

这样,有人设定了它,或者没有。如果他们没有,那就是零,你可以测试一下:

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

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