2016-07-27 70 views
2

可有人请帮助我理解为什么在下面的代码将有一个像这样的输出:迅速变量范围

[< + 37.49638550,-122.31160280> +/-5.00米(速度32.65 MPS /当然 294.26)@ 16年7月27日,上午04时34分19秒东部时间]

N/A贝尔蒙特贝尔蒙特

贝尔蒙特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设置为类似Apple,City Bicycle RideCity RunFreeway Drive

我跑的Xcode 7.3.1(7D1014)

+0

'reverseGeocodeLocation'异步工作。完成处理程序总是在'didUpdateLocations'委托方法末尾的'print'行之后调用**。 – vadian

+0

这是我的第一个猜测,但是localityVC和localityGlobal也应该打印“n/a”,不是? – rockhammer

回答

1

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

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

+0

保留它们的优先值! – rockhammer