如何解决CLLocation Manager:选择UserDefaults时运行的代码
我希望使用CLLocation Manager获取当前位置。第一次时一切都很好,但是当我单击“使用时授权”选项时,将其设置为我的user.defaults。因此,当我第二次请求时,地图转到“无处”并且我没有得到我的位置。如果我按下user.defaults进行授权,该如何解决?
//Set up the Region For the Map
fileprivate func setupRegionForMap() {
// Create Center of Map: Current Location
let centerCoordinate = CLLocationCoordinate2D(latitude: userLocation.latitude,longitude:
userLocation.longitude)
// Create how wide + tall map should be
let span = MKCoordinateSpan(latitudeDelta: 0.015,longitudeDelta: 0.015)
// Takes above two inputs and creates a region
let region = MKCoordinateRegion(center: centerCoordinate,span: span)
mapView.setRegion(region,animated: true)
locationManager.stopUpdatingLocation()
}
// Gets Users First Location and then centers the MapView based off of the latitude/latitude of
user's first location.
func locationManager(_ manager: CLLocationManager,didUpdateLocations locations: [CLLocation]) {
guard let firstLocation = locations.first else { return }
mapView.setRegion(.init(center: firstLocation.coordinate,span: .init(latitudeDelta: 0.1,longitudeDelta: 0.1)),animated: false)
// Once received,stops receiving location to save battery power
gotLocation()
locationManager.stopUpdatingLocation()
}
// Determines authorization
func locationManager(_ manager: CLLocationManager,didChangeAuthorization status:
CLAuthorizationStatus) {
switch status {
case .authorizedWhenInUse:
print("Received authorization of user location")
//starts to update location
locationManager.startUpdatingLocation()
default:
print("Failed to authorize")
}
}
// Request User's Location
fileprivate func requestUserLocation() {
locationManager.requestWhenInUseAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.delegate = self
}
func gotLocation() {
cityStateLabel.isHidden = false
latLonLabel.isHidden = false
cremImgView.isHidden = false
testButtonOutlet.setTitle("Test Connection",for: .normal)
currentLocation = locationManager.location
currentLocation.fetchCityAndState { city,state,error in
guard let city = city,let state = state,error == nil else {return}
print(city + "," + state)
self.cityStateLabel.text = "\(city),\(state)"
self.latLonLabel.text = "Latitude: \(self.currentLocation.coordinate.latitude),Longitude: \
(self.currentLocation.coordinate.longitude)"
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。