如何获得用户的经纬度

问题描述 投票:-1回答:2

我试图获取用户的纬度和经度值,但CLLocationManagerDelegate的方法没有被调用。提前感谢任何可以帮助我解决此问题的人。

import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

    var locationmanager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()
        locationmanager.delegate = self;
        locationmanager.desiredAccuracy = kCLLocationAccuracyBest
        locationmanager.requestAlwaysAuthorization()
        locationmanager.startUpdatingLocation()
    }

    //MARK: - location delegate methods
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        let userLocation :CLLocation = locations[0] as CLLocation
        print("user latitude = \(userLocation.coordinate.latitude)")
        print("user longitude = \(userLocation.coordinate.longitude)")
    }
}
ios swift4 core-location
2个回答
1
投票

你通常可以。要访问用户的当前位置,您需要物理设备。

尽管如此,还是有第二种方法可以使用工具栏中控制台上方的模拟位置选项模拟模拟器上的位置。应用程序运行时,此选项可用。

单击它以查看位置列表并选择位置以在模拟器上获取设备位置。它不是当前位置,但Simulate Location会将模拟器位置设置到您选择的位置。见下图:

Simulate Location

您还可以添加自定义GPX文件以加载当前位置。您还可以从模拟器的调试菜单中添加您的客户位置。见下图:

Customer Location

我希望这能帮到您。


0
投票

导入以下框架

Import CoreLocation

如果你想要显示地图

Import MapKit

您可以通过声明CLLocationManager实例来确定用户的当前位置:

let locationManager = CLLocationManager()

viewDidLoad()中你必须实例化CLLocationManager类,如下所示:

// Ask for Authorisation from the User.
self.locationManager.requestAlwaysAuthorization() 
// For use in foreground
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
    locationManager.startUpdatingLocation()
}

然后在CLLocationManagerDelegate方法中,您可以获得用户的当前位置坐标:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    guard let locValue: CLLocationCoordinate2D = manager.location?.coordinate else { return }
    print("locations = \(locValue.latitude) \(locValue.longitude)")
}

在info.plist中,您必须添加确保您设置了以下隐私权限。此外,确保模拟器的位置服务为ON。

  • 隐私 - 位置始终和何时使用用法说明
  • 隐私 - 使用时的位置用法说明
© www.soinside.com 2019 - 2024. All rights reserved.