繁体   English   中英

无法获取用户的当前位置

[英]Can't get user's current location

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

我已经尝试了很多来自google结果的解决方案,但是仍然无法正常工作...。

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

似乎该应用程序从未运行过“ 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)

}

import CoreLocation吗?

首先创建一个变量, let myLocation = CLLocation()

您可以创建一个函数并在viewDidLoad中调用mLocation,而不是在viewDidLoad中拥有太多功能:

func mLocation(){
    cloaction.delegate = self
    cloaction.desiredAccuracy = kCLLocationAccuracyBest
    cloaction.requestWhenInUseAuthorization()

    if CLLocationManager.locationServicesEnabled(){
        cloaction.startUpdatingLocation()
    }
}

这就是您需要的所有clocation

LocationManager也可以更新

 func locationManager(_ manager: CLLocationManager, didUpdateLocations locations:[CLLocation]){
        let newLocation = locations[0]

        print("\(myLocation.coordinate.latitude)")
        print("\(myLocation.coordinate.longitude)")
    }

实际上,原因很简单:仅在更改位置时才调用didUpdateLocation方法。 您的Mac在特定位置且不会移动,因此这就是它无法正常工作的原因。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM