【问题标题】:CLLocationManager() Location is nil in simulatorCLLocationManager() 模拟器中的位置为零
【发布时间】:2017-07-10 10:58:56
【问题描述】:

我正在尝试获取latitudelongitude,但位置始终为nil

class FinalizeOrderController: UIViewController {

    var locManager = CLLocationManager()
    var currentLocation: CLLocation!

    override func viewDidLoad() {
        super.viewDidLoad()
        currentLocation = CLLocation()
        locManager.requestWhenInUseAuthorization()

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func FinaliseOrder(_ sender: Any) {
        if (CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedWhenInUse ||
            CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedAlways) {
            currentLocation = locManager.location
            print(locManager.location?.coordinate.latitude) //prints nil
            print(currentLocation.coordinate.longitude) //fatal error: unexpectedly found nil while unwrapping an Optional value
        }


        lbl1.text = "\(currentLocation.coordinate.longitude)"
        lbl2.text = "\(currentLocation.coordinate.latitude)"
    }

我添加 info.plist 键并从Xcode 运行模拟器位置,并从调试中选择模拟器位置,但并非总是nil

【问题讨论】:

  • 检查模拟器 - 调试 - 位置不为空
  • 我选择苹果
  • 您不能只访问location 属性。需要等待didUpdateLocations委托方法的回调。
  • 我不需要位置更新,现在它运行良好并打印苹果位置我注意到当我选择自定义位置时更改位置需要时间 苹果位置仍然是模拟器位置
  • 确保在模拟器中调试 -> 位置未设置为无

标签: ios swift swift3 ios-simulator cllocationmanager


【解决方案1】:

试试这个:

var locationManager: CLLocationManager?
var currentLocation:CLLocation?

符合委托

class ViewController: UIViewController,CLLocationManagerDelegate

在 ViewDidLoad 中

 override func viewDidLoad() {

        super.viewDidLoad()
        locationManager = CLLocationManager();
        locationManager.delegate = self;
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        let authorizationStatus = CLLocationManager.authorizationStatus()

        if (authorizationStatus == CLAuthorizationStatus.NotDetermined) {
            locationManager.requestWhenInUseAuthorization()
        } else {
            locationManager.startUpdatingLocation()
        }
    }

在委托中

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
     currentLocation = locations[locations.count-1] as CLLocation

    print("locations = \(currentLocation)")
   // lbl1.text = "\(currentLocation.coordinate.latitude)";
   // lbl2.text = "\(currentLocation.coordinate.longitude)";
}

在按钮操作中

@IBAction func FinaliseOrder(_ sender: Any) {

        lbl1.text = "\(currentLocation.coordinate.longitude)"
        lbl2.text = "\(currentLocation.coordinate.latitude)"
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-23
    • 2018-03-05
    • 1970-01-01
    • 2014-10-18
    • 1970-01-01
    • 1970-01-01
    • 2010-12-06
    • 1970-01-01
    相关资源
    最近更新 更多