获取用户的当前位置但返回 "Optional" California.. 等等

Getting user's current location but getting back "Optional" California.. etc

我正在尝试使用 Swift 获取用户的当前位置。这是我目前正在使用的:

import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

    let locationManager = CLLocationManager();

    //Info about user
    @IBOutlet weak var userTF: UITextField!
    @IBOutlet weak var BarbCustTF: UITextField!

    override func viewDidLoad()
    {
        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.

        self.locationManager.delegate = self;
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        self.locationManager.requestWhenInUseAuthorization();
        self.locationManager.startUpdatingLocation();

    }

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



    // GPS STUFF
    // UPDATE LOCATION
    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        CLGeocoder().reverseGeocodeLocation(manager.location!) { (placemarks, ErrorType) -> Void in
            if(ErrorType != nil)
            {
                print("Error: " + ErrorType!.localizedDescription);
                return;
            }

            if(placemarks?.count > 0)
            {
                let pm = placemarks![0] ;
                self.displayLocationInfo(pm);
            }
        }
    }

    // STOP UPDATING LOCATION
    func displayLocationInfo(placemark: CLPlacemark)
    {
        self.locationManager.stopUpdatingLocation();
        print(placemark.locality);
        print(placemark.postalCode);
        print(placemark.administrativeArea);
        print(placemark.country);
    }

    // PRINT OUT ANY ERROR WITH LOCATION MANAGER
    func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
        print("Error: " + error.localizedDescription);
    }

一切似乎都工作正常,但我得到的输出真的很奇怪,并且在它前面说 Optional,而且绝对(不幸的是)不是我当前的位置。

这是我将它打印到控制台时得到的输出

可选("Cupertino")

可选(“95014”)

可选("CA")

可选("United States")

我尝试过的事情: 1) 在我的 info.plist 中,我有:NSLocationWhenInUseUsageDescription 2) 我也听说发生了奇怪的事情,我尝试去 Debug>>Location>> 并将其更改为 in city 和各种事情(没有帮助)

我认为问题出在我的函数 LocationManager 中,与 "wrapping" 之类的东西有关?我不确定,这是我第一天用 iOS 和 Swift 编程,我真的不知道包装是什么,但我认为这可能是我所看到的情况在互联网上...基本上我不明白为什么我打印出一些默认的苹果位置(加利福尼亚..等等等等)我不住在卡利(不幸的是)。

而不是这个

print(placemark.locality);

这样做

if let locality = placemark.locality {
    print(locality)
}

这里的 if let 模式是一种只打印 locality 的方式,如果它不是 nil。在这种情况下就是这样做的。

如果您确定 locality 永远不会 nil,您可以

print(placemark.locality!)

但如果 locality 恰好是 nil,您的应用程序将在该行崩溃。