【问题标题】:Problems with location swift 3定位问题 swift 3
【发布时间】:2017-04-20 12:15:19
【问题描述】:

我想使用位置数据制作一个简单的 iOS 应用程序。不幸的是,在设备和模拟器上进行测试时,我收到“nil”,即使我在模拟器上输入“当前位置”调试代码。 这是我第一次在 swift 3 上使用 CoreLocation,所以我使用了与以前相同的方法。

import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

    @IBOutlet weak var latitudeLabel: UILabel!
    @IBOutlet weak var longitudeLabel: UILabel!

    var locationManager:CLLocationManager?
    var currentLocation:CLLocation?

    override func viewDidLoad() {
        super.viewDidLoad()
        let locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestAlwaysAuthorization()
        locationManager.startUpdatingLocation()
        updateLabels()
        // Do any additional setup after loading the view, typically from a nib.
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        self.currentLocation = locations[0]
    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print(error)
    }

    func updateLabels() {
        latitudeLabel.text = String(describing: currentLocation?.coordinate.latitude)
        longitudeLabel.text = String(describing: currentLocation?.coordinate.longitude)
        print(currentLocation)
}

}

当然,我已经在 Info.plist 中编写了所有必要的隐私密钥。

当我尝试打印 currentLocation 时,我收到 nil。 在上次启动时,我发现了这样的问题,然后出现了警报,但立即消失了

【问题讨论】:

  • “我收到'nil'”是什么意思?请澄清您的问题。
  • 感谢您的回复。编辑描述。

标签: ios swift swift3 core-location


【解决方案1】:

viewDidLoad 中,您将CLLocationManager 保存在局部变量中,但从不将其保存到您的属性中。因此,它超出范围并被释放,可能永远不会调用您的委托方法。

直接更新您的资源,或者在您配置完位置管理器后,请务必发送self.locationManager = locationManager。我可能会直接更新它:

override func viewDidLoad() {
    super.viewDidLoad()

    locationManager = CLLocationManager()
    locationManager?.delegate = self
    locationManager?.desiredAccuracy = kCLLocationAccuracyBest
    locationManager?.requestAlwaysAuthorization()
    locationManager?.startUpdatingLocation()
    // updateLabels()
}

然后,正如 rmaddy 指出的那样,在didUpdateLocations 中更新您的标签:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    guard let location = locations.last, location.horizontalAccuracy >= 0 else { return }

    currentLocation = location
    updateLabels()
}

【讨论】:

    【解决方案2】:

    您从错误的地方拨打updateLabels。您需要从 locationManager(_:didUpdateLocations) 方法内部调用它。由于可能在后台线程上调用该委托方法,因此请确保将调用包装到 updateLabels 使用 DispatchQueue.main.async

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-23
      • 1970-01-01
      相关资源
      最近更新 更多