ios - 位置问题 swift 3

标签 ios swift swift3 core-location

我想制作一个简单的 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 中编写了所有必要的隐私 key 。

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

最佳答案

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

要么直接更新您的属性,要么在您配置完位置管理器后,确保执行 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()
}

关于ios - 位置问题 swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40985512/

相关文章:

ios - 在本地通知中点击后无法在特定 View Controller 中打开应用程序

ios - 检测 - 弹出到根 VC 后,VIewctroller 未从内存中删除

ios - 不要一次上传所有东西 Firebase

ios - 本地通知 swift 3

ios - 在 map View 上显示比例

ios - 将文本从 uitextfield 存储到字典键

ios - 可以使用终端向现有配置文件添加或删除 UDID 吗?

ios - 在 Swift 3 中使用 Stream 打开与 SMTP 服务器的套接字连接

Xcode 调试器错误 : use of unresolved identifier 'X' for global variables

ios - ios Swift 3 app在didRegisterForRemoteNotificationsWithDeviceToken函数中崩溃