ios – 位置问题迅速3

ios – 位置问题迅速3,第1张

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

import UIKitimport CoreLocationclass 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.
随着最后一次发射,我发现了这样的问题,而不是出现警报,但立刻消失了

解决方法 在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()}
总结

以上是内存溢出为你收集整理的ios – 位置问题迅速3全部内容,希望文章能够帮你解决ios – 位置问题迅速3所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1062896.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-26
下一篇 2022-05-26

发表评论

登录后才能评论

评论列表(0条)

保存