ios - 我的简单 map 项目无法在模拟器中获取和显示我的位置

标签 ios ios8 mkmapview ios-simulator xcode7

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

我有一个显示 map 的 UIViewController 并且应该获取我的位置并将其显示在 map 上:

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 -> Location -> Custom Location ... 并设置芬兰赫尔辛基的经度和纬度,如下所示: enter image description here

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

=====更新====

我也试过this当我的应用程序正在运行时,它也无济于事。

最佳答案

您正在请求用户的位置,但实际上并未对响应执行任何操作。成为位置管理器的委托(delegate)并响应授权更改。

这段代码适用于 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
    }
}

关于ios - 我的简单 map 项目无法在模拟器中获取和显示我的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36250101/

相关文章:

ios - 如何检测用户是否在我的应用程序中为本地通知设置了横幅样式警报或 'normal' 样式警报?

ios - iOS8 中设备旋转后的 ViewController 偏移量

iphone - 移动自定义注释以显示用户位置

ios - 获取 MKMapView 以响应 touch up inside 事件

ios - CLGeocoder reverseGeocodeLocation 返回具有不同纬度/经度的地标? (附 Playground 示例)

ios - 找不到 GMSMarker 的协议(protocol)声明

iphone - 子类化 UITableViewCell 后标签将不会显示文本

iOS:如何避免/禁用默认调用提醒?

html - Iphone 6 或 Ios 8 safari 图像随机重复问题

uiimage - 在 iOS8 中使用 MPMediaItemArtwork 的 imageWithSize Flakey