Swift - 用户位置问题

时间:2015-07-14 12:59:30

标签: ios swift mapkit

我刚刚开始使用swift,我遇到了问题。我已经阅读了有关用户位置和地图工具包的各种主题,但无法解决我的问题。我运行了代码,可以根据需要创建区域,我可以放大用户位置。

我已将代码配对,以尝试找到问题,下面的代码如下。问题是当您尝试运行崩溃应用程序的模拟器时,用户位置将返回为零值。我完成了授权用户位置后我做错了什么,所以肯定不应该回来。有一次,我有代码放大用户位置,最初在其他地方设置区域并调用函数进行缩放,但如果你最初尝试调用用户位置,它总是为零,所以你不能初始化地图放大到用户在哪里是我想要的。

import UIKit
import MapKit

class MapController: UIViewController, CLLocationManagerDelegate {

@IBOutlet weak var mapView: MKMapView!

// MARK: - location manager to authorize user location for Maps app

var locationManager = CLLocationManager()

func checkLocationAuthorizationStatus() {
    if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse {
        mapView.showsUserLocation = true
    } else {
        locationManager.requestWhenInUseAuthorization()
    }
}

override func viewDidLoad() {
    super.viewDidLoad()

    checkLocationAuthorizationStatus()

    var userLocation = locationManager.location

    println("\(userLocation.coordinate.latitude)")

    println("\(userLocation.coordinate.longitude)")

    // Do any additional setup after loading the view.
    }

}

1 个答案:

答案 0 :(得分:1)

首先,CLLocationManager异步更新用户位置。这意味着,即使您致电startUpdatingLocation(),您的位置也会为nil,直到位置经理返回新位置。

其次,在您的代码中,您实际上并没有调用此方法。如果您需要能够存储用户位置,那么您应该将代码更改为:

import UIKit
import MapKit

class MapController: UIViewController, CLLocationManagerDelegate {

@IBOutlet weak var mapView: MKMapView!

// MARK: - location manager to authorize user location for Maps app

lazy var locationManager: CLLocationManager = {
    var manager = CLLocationManager()
    manager.delegate = self
    return manager
}()

func checkLocationAuthorizationStatus() {
    if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse {
        mapView.showsUserLocation = true
        locationManager.startUpdatingLocation()
    } else {
        locationManager.requestWhenInUseAuthorization()
    }
}

override func viewDidLoad() {
    super.viewDidLoad()

    checkLocationAuthorizationStatus()

    //location is nil at this point because location update is
    //an asynchronous operation!
    //var userLocation = locationManager.location

    //println("\(userLocation.coordinate.latitude)")

    //println("\(userLocation.coordinate.longitude)")

    // Do any additional setup after loading the view.
}

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let location = locations.last {
        //this is the place where you get the new location
        println("\(location.coordinate.latitude)")

        println("\(location.coordinate.longitude)")
    }
}

只有一件小事需要注意。在最后一个函数中,我使用的是参数locations: [CLLocation]。这在Swift 2.0中是绝对正确的,但在Swift 1.2中它可能是locations: [AnyObject],在这种情况下你必须自己做一个有条件的向下转换。

如果这对您有用,请告诉我