首页 > 解决方案 > 无法获取用户当前位置

问题描述

我的应用程序有一个简单的目标,即获取当前坐标,并使用它们在地图视图上添加注释。

我已经从谷歌结果中尝试了很多解决方案,但它仍然无法正常工作......

调试区域从不显示“locationManager did UpdateLocation”,我在函数中打印的消息......

似乎应用程序从未运行过“更新位置”功能,甚至已经调用了 startUpdatingLocation()?


在 info.plist 中添加位置隐私字符串:完成。

在我的 Mac Pro 上打开 GPS:完成。

Xcode 版本:10.1

MacOS:10.13.6(高山脉)


let cloaction = CLLocationManager()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    MapView.delegate = self
    MapView.showsScale = true
    MapView.showsPointsOfInterest = true
    MapView.showsUserLocation = true

    cloaction.requestAlwaysAuthorization()
    cloaction.requestWhenInUseAuthorization()

    if CLLocationManager.locationServicesEnabled() {
        print("IN")

        cloaction.delegate = self
        cloaction.desiredAccuracy = kCLLocationAccuracyBest
        cloaction.startUpdatingLocation()
    }        
}

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    print("locationManager did UpdateLocation")

    let location = CLLocationCoordinate2D(latitude: (locations.first?.coordinate.latitude)!, longitude: (locations.first?.coordinate.longitude)!)

    currentLat = (locations.first?.coordinate.latitude)!
    currentLon = (locations.first?.coordinate.longitude)!

    let span = MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01)

    MapView.setRegion(MKCoordinateRegion(center: CLLocationCoordinate2DMake(currentLat,currentLon), span: span), animated: true)
    MapView.showsUserLocation = true

    print(locations.first?.coordinate.latitude)
    print(locations.first?.coordinate.longitude)

}

标签: iosswiftmapkit

解决方案


是的!最后...感谢您的回答,确实需要在设备上运行,感谢Kosuke Ogawa的建议,以及每个人的指导,我是新手学习swift,第一次在这里提问,很有趣,谢谢大家。(但如果答案是评论,我不知道如何接受答案?有人教我怎么做?)


推荐阅读