我是Swift
的新用户,我希望从当前位置获取latitude & longitude
。使用这些latitude & longitude
自动填充UITextField
获取城市& Swift-3
中UITextField上的国家/地区名称。提前谢谢。
答案 0 :(得分:0)
请尝试以下方法:
import Foundation
import CoreLocation
class LocationViewController : UIViewController {
@IBOutlet weak var txtField: UITextField!
var locationManager = CLLocationManager()
override func viewDidLoad()
{
super.viewDidLoad()
self.getCurrentAddress { currentAddress, error in
if let address = currentAddress, let city = address["City"] as? String, let country = address["Country"] as? String {
self.txtField.text = "\(city), \(country)"
}
}
}
func getCurrentAddress(completion: @escaping (_ currentAddress: [String:Any]?, _ error: Error?) -> ()) {
var currentLocation: CLLocation!
let authStatus = CLLocationManager.authorizationStatus()
self.locationManager.requestWhenInUseAuthorization()
if authStatus == CLAuthorizationStatus.authorizedWhenInUse || authStatus == CLAuthorizationStatus.authorizedAlways {
currentLocation = locationManager.location
let longi = currentLocation.coordinate.longitude
let lat = currentLocation.coordinate.latitude
let geoCoder = CLGeocoder()
geoCoder.reverseGeocodeLocation(currentLocation) { placemarks, error in
if let e = error {
completion(nil, e)
} else {
let placeArray = placemarks
let placeMark = (placeArray?[0])!
guard let currentAddress = placeMark.addressDictionary as? [String:Any] else {
return
}
completion(currentAddress, nil)
}
}
}
}
}
需要在plist文件中设置NSLocationWhenInUseUsageDescription