앱 위임에 현재 위치를 가져 오는 기능을 설정하려고하지만 하단에 print(city)
이 있으면 "hello"라는 전역 변수에 원래 초기화 된 값이 반환됩니다. CLGeocoder에서 값을 업데이트했지만 가 완료되기 전에명세서가 전역 변수를 신속하게 변경하지 못한다면
AppDelegate:
import UIKit
import CoreData
import CoreLocation
let appDelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
var country = "hello"
var city = "hello"
func setupLocationManager(){
let locationManager = CLLocationManager()
locationManager.requestAlwaysAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
}
// Below method will provide you current location.
func getLocation() -> [String]{
let manager = CLLocationManager()
manager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
manager.requestAlwaysAuthorization()
manager.startUpdatingLocation()
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestAlwaysAuthorization()
manager.startUpdatingLocation()
let selflocation = manager.location
let latitude: Double = selflocation!.coordinate.latitude
let longitude: Double = selflocation!.coordinate.longitude
print("current latitude :: \(latitude)")
print("current longitude :: \(longitude)")
let location = CLLocation(latitude: latitude, longitude: longitude) //changed!!!
CLGeocoder().reverseGeocodeLocation(location, completionHandler: {(placemarks, error) -> Void in
print(location)
if error != nil {
print("Reverse geocoder failed with error" + (error?.localizedDescription)!)
}
let pm = placemarks![0]
let speed = (selflocation?.speed)!
city = pm.addressDictionary!["City"]! as! String
country = pm.addressDictionary!["Country"]! as! String
if (placemarks?.count)! > 0 {
}
else {
print("Problem with the data received from geocoder")
}
})
print(city)
return [city as! String, country as! String]
}
클로저 안에 인쇄물 (도시)을 이동하면 올바른 응답이 인쇄되지만 클로저 안에서는 함수를 반환 할 수 없으므로 작동하지 않습니다. –