Swift3 如何使用swift中的CLLocationManager从当前位置获取经纬度?
我是Swift3 如何使用swift中的CLLocationManager从当前位置获取经纬度?,swift3,cllocationmanager,Swift3,Cllocationmanager,我是Swift新手,我想从当前位置获取纬度和经度。使用这些纬度和经度通过在Swift-3的UITextField中获取城市和国家名称,自动填充UITextField。提前感谢。请尝试以下选项: import Foundation import CoreLocation class LocationViewController : UIViewController { @IBOutlet weak var txtField: UITextField! var locationMa
Swift
新手,我想从当前位置获取纬度和经度。使用这些纬度和经度
通过在Swift-3
的UITextField中获取城市和国家名称,自动填充UITextField
。提前感谢。请尝试以下选项:
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文件中设置nsLocationWhenUsageDescription
我将尝试@Vini App,并使用上面的代码@Vini App更新答案,让您知道我将在哪里获得lat long。请检查我将检查您的更新答案,并让您知道@Vini app使用了您的代码,但应用程序在此行“let longi=currentLocation.coordinate.longitude”@Vini app崩溃