我正在尝试获取在模拟器上运行的用户位置,我获得了默认地址,但至少我知道它正在运行。 我试图在我的设备上运行它,但是没有用。 在写这个问题之前,我试图寻找一种解决方案,但是找不到适合我的东西。 这是我的代码:
LocationManager:
class LocationManager: NSObject, CLLocationManagerDelegate {
static let shared = LocationManager()
var locationManager: CLLocationManager!
var geoCoder = CLGeocoder()
var callBack:((String)->())?
override init() {
super.init()
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.activityType = .other
locationManager.requestWhenInUseAuthorization()
}
func checkIfLocationIsEnabled() -> Bool{
return CLLocationManager.locationServicesEnabled()
}
func getUserLocation(){
locationManager.requestLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]){
let userLocation: CLLocation = locations[0] as CLLocation
geoCoder.reverseGeocodeLocation(userLocation) { (placemarks, err) in
if let place = placemarks?.last{
self.callBack?(place.name!)
}
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print(error)
}
}
这是我的getLocation(只需调用getUserLocation并设置我从回调中获取的地址):
func getLocation(_ label: UILabel) -> String{
guard let comment = self.mView.addCommentTextField.text else { return ""}
LocationManager.shared.getUserLocation()
var addressString = ""
LocationManager.shared.callBack = { address in
DispatchQueue.main.async {
label.text = "\(address), \(comment)"
addressString = address
}
}
return addressString
}
这就是我所谓的getLocation:
self.mView.inLabel.isHidden = false
self.getLocation(self.mView.inLabel)
答案 0 :(得分:0)
实际上仔细查看您的代码,发现您正在询问这样的权限:
locationManager.requestWhenInUseAuthorization()
但是requestWhenInUseAuthorization()
是异步调用,您需要先等待用户响应,然后才能使用任何位置服务:
当前授权状态为
CLAuthorizationStatus.notDetermined
时,此方法异步运行 ,并提示用户向应用授予使用位置服务的权限。
(source)
还要注意,它仅在状态为notDetermined
时才有效。任何其他状态都不会触发它。所以首先:
if CLLocationManager.authorizationStatus() == .authorizedWhenInUse {
// already authorized, can use location services right away
}
if CLLocationManager.authorizationStatus() == .notDetermined {
locationManager.requestWhenInUseAuthorization()
// wait, don't call any location-related functions until you get a response
}
如果将位置权限设置为其他任何权限,也无济于事。
然后您的课程已经是CLLocationManagerDelegate
,所以:
func locationManager(_ manager: CLLocationManager,
didChangeAuthorization status: CLAuthorizationStatus) {
// do something with new status, e.g.
if status == .authorizedWhenInUse {
// good, now you can start accessing location data
}
// otherwise, you can't