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 (将#修改为@)