ios - 无法获取用户当前位置

标签 ios swift mapkit

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

我已经尝试了很多来自谷歌结果的解决方案,但它仍然不起作用......

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

应用程序似乎从未运行过“did UpdateLocation”函数,甚至调用了 startUpdatingLocation() ?

<小时/>

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

打开 Mac Pro 上的 GPS:完成。

Xcode 版本:10.1

MacOS:10.13.6(High Sierra)

<小时/>
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)

}

最佳答案

实际上原因很简单:您调用 didUpdateLocation 方法,该方法仅在您更改位置时调用。您的 Mac 位于某个位置且不动,这就是它无法工作的原因。

关于ios - 无法获取用户当前位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53218908/

相关文章:

ios - map 套件的用户体验

iphone - 如果我在调用 textFieldShouldReturn 时返回 "YES"或 "NO"有什么区别

ios - 更新 CALayer 的旋转

generics - Swift 通用对象/JSON 序列化

ios - Swift 4 可解码 : The given data was not valid JSON

ios - 在表格 View 中使用两个不同的单元格

ios - 有没有更好的方法在 Swift 中做这个滚动动画?

ios - AVCam 未全屏

swift - 缩小 UICollectionView 和 UITableView 的 header

swift - 对 Mapkit 对象值变化使用react