2016-07-27 108 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