首页 > 解决方案 > 运行模拟器时没有打印坐标,但是当我在我的 iPhone 上运行程序时

问题描述

我有以下代码

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, CLLocationManagerDelegate {

    var locationManager = CLLocationManager()
    var coordinates: String?

    override func viewDidLoad() {
        super.viewDidLoad()
        self.locationManager.requestAlwaysAuthorization()

        if CLLocationManager.locationServicesEnabled() {
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.startUpdatingLocation()
        }
    }


func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    //updates the user's location as the user moves
    let location: CLLocation = locations[0] as CLLocation
    coordinates = "\(location.coordinate.latitude),\(location.coordinate.longitude)"
    print(coordinates!)
}

当我在模拟器上运行它时,程序运行良好,但它不打印坐标。当我在 iPhone 上运行它时,它会打印坐标。我需要更改 Xcode 设置中的某些内容以解决此问题吗?此外,当我尝试在另一个函数中使用“坐标”变量时,我得到一个错误,说编译器正在找到 nil,即使我在 locationManager 函数中为其分配了一个值,所以我猜测这两个问题是相关的。提前致谢

标签: swiftcore-locationcllocationmanager

解决方案


您可以在运行应用程序时使用“模拟位置”按钮在模拟器上模拟位置:

在此处输入图像描述

您可以选择现有位置之一,也可以创建 GPX 文件(例如,不是静态单点,而是模拟位置不断变化的路线)。我建议您使用https://mapstogpx.com/创建 GPX 文件。


推荐阅读