2016-12-05 103 views
4

我想使用位置数据制作一个简单的iOS应用程序。不幸的是,即使在模拟器上输入“当前位置”调试代码,在设备和模拟器上同时测试时,我也会收到'无'。 这是我第一次在Swift 3上使用CoreLocation,所以我使用了和前面一样的方法。位置快速问题3

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时,我收到零。 随着最后一次发布,我发现这样的问题,而不是一个警报正在出现,但立即消失

+0

你说的“我接受‘零’”是什么意思?请澄清你的问题。 – rmaddy

+0

感谢您的回复。编辑说明。 –

回答

4

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() 
} 
1

您正在呼叫updateLabels从错误的地方。您需要从locationManager(_:didUpdateLocations)方法中调用它。由于该委托方法可能会在后台线程中调用,因此请确保使用DispatchQueue.main.async将调用包装为updateLabels