CLLocationManager()模拟器中的位置为nil

时间:2017-07-10 10:58:56

标签: ios swift swift3 ios-simulator cllocationmanager

我尝试获取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

1 个答案:

答案 0 :(得分:2)

试试这个:

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)"
}