Swift -用户位置问题



我刚开始使用swift,我遇到了一个问题。我已经阅读了关于用户位置和地图套件的各种线程,但无法解决我的问题。我已经运行了代码,可以创建我想要的区域,我可以放大用户位置。

我把代码配对回去,试图找到问题,剩下的代码在下面。问题是,当你尝试运行导致应用崩溃的模拟器时,userlocation会以nil值返回。我做错了什么,因为我已经完成了授权用户位置,所以它肯定不应该返回nil。在某一点上,我有代码缩放用户位置后,最初设置一个区域在其他地方,并调用一个函数来做缩放,但如果你最初尝试调用用户位置总是nil,所以你不能初始化地图缩放到用户所在的地方,这是我想要的。

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.
    }
}

首先,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],在这种情况下,你必须自己做一个条件向下转换。

让我知道这是否适合你

最新更新