2017-05-10 127 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

位置管理器是一個異步函數。這意味着您的代碼將啓動該功能,但會繼續執行下一段代碼,而不是等待獲取該位置,該位置將在稍後完成。

所以,即使您的打印功能之前調用您的更新位置,由當時的代碼執行它並沒有得到該地點尚未打印和當前城市是零。

打印從位置管理器功能的名稱或添加完成關閉。這應該夠了吧。