关闭wrt的快速变量范围CLGeocoder()

时间:2016-07-27 09:24:42

标签: swift scope closures clgeocoder

有人可以帮我理解为什么在下面的代码中会有这样的输出:

  

[1 + 37.49638550,-122.31160280> +/- 5.00米(速度32.65 mps /航向   294.26)@ 7/27 / 16,4:34:19 AM东部夏令时间]

     

n / a Belmont Belmont

     

Belmont 1

也就是说,为什么变量locality在特定点打印时具有值“n / a”,而localityVC& localityGlobal从不这样做?这纯粹是范围​​问题还是与CLGeocoder()有关?感谢

import UIKit
import MapKit
import CoreLocation

var localityGlobal: String = "n/a"

class ViewController: UIViewController, CLLocationManagerDelegate {

    let locationManager = CLLocationManager()
    var localityVC: String = "n/a"

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        print("hello")

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

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        print(locations)

        let userLocation: CLLocation = locations[0]
        var locality: String = "n/a"

        CLGeocoder().reverseGeocodeLocation(userLocation, completionHandler: {(placemarks, error) -> Void in
            if error != nil {
                print("CLGeocoder.reverseGeocodeLocation() failed")
                return
            }
            if placemarks!.count > 0 {
                locality = placemarks![0].locality!
                self.localityVC = placemarks![0].locality!
                localityGlobal = placemarks![0].locality!
                print(locality, placemarks!.count)

            } else {
                print("CLGeocoder.reverseGeocodeLocation() error in geocoder data")
            }
        })

        print(locality, localityVC, localityGlobal)
    }

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

为了使上述内容能够运行,您还需要:

  1. Build Phases -> Link Binary with Libraries包含 CoreLocation.framework
  2. Info.plist必须包含变量 NSLocationWhenInUseUsageDescriptionNSLocationAlwaysUsageDescription设置,
  3. Simulator -> Debug -> Location设置为AppleCity Bicycle RideCity RunFreeway Drive
  4. 我正在运行xcode 7.3.1(7D1014)

1 个答案:

答案 0 :(得分:1)

这不是范围问题,而是时间问题。你得到n / a,因为在执行print语句时闭包还没有运行。

其他变量保留先前调用的值。