2017-05-10 130 views
-2

我不会打印在控制台currentCity,对于使用城市名称的另一个功能!请帮帮我。我如何利用变量从功能其他功能SWIFT 3

var locationManager = CLLocationManager() 

var currentCity: String? 

override func viewDidLoad() { 
    super.viewDidLoad() 


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

    print(currentCity) //----error not printing CITY NAME 
} 

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

    let userLocation: CLLocation = locations[0] 

    CLGeocoder().reverseGeocodeLocation(userLocation) { (placemarks, error) in 

     if error != nil { 

      print(error?.localizedDescription as Any) 

     } else { 

      if let placemark = placemarks?[0] { 

       if let city = placemark.addressDictionary?["City"] as? NSString { 

        self.cityLbl.text = city as String 
        self.currentCity = city as String 

       } 
      } 
     } 
    } 

} 
+1

将打印线在'didUpdateLocations'委托方法在'else'范围的端部。 – vadian

+0

我需要在另一个功能中使用城市名称!你的变体已经工作,但我不需要在didUpdateLocations中打印。我不会把这个城市名称,并在json –

+0

中使用这个名字认为异步并从委托方法调用*其他函数*。 – vadian

回答

0

您需要didUpdateLocations打印城市。

   if let city = placemark.addressDictionary?["City"] 
             as? NSString { 

        self.cityLbl.text = city as String 
        self.currentCity = city as String 
        print(currentCity) // here you get string 
         // call that function here 
        self.myfunction(cityName: currentCity) 

       } 

功能

func myfunction(cityName : String) -> Void { 
     // your string with city name 
    } 
+0

我需要在另一个功能中使用城市名称!你的变体已经工作,但我不需要在didUpdateLocations中打印。我不会把这个城市名称,并在json –

+0

中使用这个名称,然后调用函数在你得到该字符串的cityname下。 – KKRocks

+0

非常感谢我的朋友!我尝试这个变体,并说你工作或否。 对不起我的英语很糟糕)我来自高加索) –

0

FUNC viewDidLoad中()被调用第一和当时的位置不被取。在func locationManager(_ manager:CLLocationManager,didUpdateLocations locations:[CLLocation])被调用后尝试打印。

+0

我试图做出新的FUNC例如:FUNC printVar(){ 打印(currentCity) } didUpdateLocations后,并调用本功能在viewDidLoad中,但再次为零! –

2

位置管理器是一个异步函数。这意味着您的代码将启动该功能,但会继续执行下一段代码,而不是等待获取该位置,该位置将在稍后完成。

所以,即使您的打印功能之前调用您的更新位置,由当时的代码执行它并没有得到该地点尚未打印和当前城市是零。

打印从位置管理器功能的名称或添加完成关闭。这应该够了吧。