我的简单地图项目没有获得&在模拟器中显示我的位置

时间:2016-03-27 17:00:18

标签: ios ios8 mkmapview ios-simulator xcode7

我正在使用XCode v7.2.1,Simulator v9.2。

我有一个UIViewController,它显示了一张地图&应该得到我的位置&在地图上显示:

import UIKit
import MapKit

class LocationVC: UIViewController, MKMapViewDelegate {
    @IBOutlet weak var map: MKMapView!

    let locationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()

        map.delegate = self
    }

    override func viewDidAppear(animated: Bool) {
        if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse {
            map.showsUserLocation = true
        } else {
            locationManager.requestWhenInUseAuthorization()
        }
    }

}

我在 info.plist 中添加了NSLocationWhenInUseUsageDescription,如下所示:

enter image description here

我还选择了Debug - >位置 - >自定义位置...并设置经度和芬兰赫尔辛基的纬度如下图所示: enter image description here

当我运行我的应用时,会显示地图,但是它没有获取我的位置。为什么? (我的意思是我在地图的任何地方都看不到蓝点。)

=====更新====

我的应用程序运行时我也尝试了this,但它也无济于事。

3 个答案:

答案 0 :(得分:7)

您正在请求用户的位置,但实际上没有对响应做任何事情。成为位置经理的代表并回应授权变更。

此代码适用于7.2.1(在Debug - > Location中选择“Apple”之后):

import UIKit
import MapKit

class ViewController: UIViewController, CLLocationManagerDelegate {
    @IBOutlet weak var map: MKMapView!

    let locationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()

        locationManager.delegate = self
    }

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)

        if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse {
            map.showsUserLocation = true
        } else {
            locationManager.requestWhenInUseAuthorization()
        }
    }

    func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
        guard status == .AuthorizedWhenInUse else { print("not enabled"); return }
        map.showsUserLocation = true
    }
}

答案 1 :(得分:0)

我同意@Casey的回答,但有时您需要使用CLLocationManagerDelegate方法做更多的事情。

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let location = locations.first {
       //reset mapView's center in case your custom location was wrong.
        map.centerCoordinate = location.coordinate
       //mannual call show annotations to avoid some bugs
        map.showAnnotations(map.annotations, animated: true)
    }
}

答案 2 :(得分:0)

你只需要添加

locationManager.delegate = self
mapView.showsUserLocation = true