RequestLocation花费的时间太长

时间:2020-04-11 07:20:00

标签: ios swift

我在Swift 5中为我的ios应用程序使用location.requestLocation。但是它花费的时间太长了。大约10秒。在线搜索解决方案时,他们说要使用startUpdatingLocation来代替。但是问题是我只想要一次,而不是连续更新。我也对它的准确性不感兴趣。 因为我只想缩放到我的Google地图位置,然后使用用户位置按距离对内容进行排序即可。最多3至4公里的位置可能是错误的,我没问题。

 override func viewDidLoad() {
        super.viewDidLoad()
        //mapView.showsUserLocation = false
        locationManager.delegate = self
        print(locationManager.distanceFilter)
        switch CLLocationManager.authorizationStatus() {
        case CLAuthorizationStatus.notDetermined, .restricted, .denied:
            locationManager.requestWhenInUseAuthorization()
        case CLAuthorizationStatus.authorizedWhenInUse, .authorizedAlways:
            requestLocation()
        @unknown default: break

        }            
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        print("\nStart of locationManager(didChangeAuthorization)")

        let authStatus = CLLocationManager.authorizationStatus()
        if authStatus == CLAuthorizationStatus.authorizedWhenInUse
            || authStatus == CLAuthorizationStatus.authorizedAlways {
            requestLocation()
        }

        print("\nEnd of locationManager(didChangeAuthorization)")
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        print("\nStart of locationManager(didUpdateLocations)")

        zoomInLocation(locations.last!)
    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        if let err = error as? CLError, err.code == .denied {
            manager.stopUpdatingLocation()
            return
        }
        print("\nlocationManager(): \(error.localizedDescription)")
    }

    private func requestLocation() {
        print("\requestLocation() called")

        // check if the location service is availalbe on that device
        if !CLLocationManager.locationServicesEnabled() {
            return
        }

        locationManager.requestLocation()
    }

    private func zoomInLocation(_ location: CLLocation) {
        loca2  = location
        let camera = GMSCameraPosition.camera(withLatitude: location.coordinate.latitude, longitude: location.coordinate.longitude, zoom: 6.0)
        (view1 as! GMSMapView).animate(to: camera)
        print("\nzoomInUserLocation(): mapView[latitude]=\(location.coordinate.latitude), locationManager[latitude]=\(String(describing: location.coordinate.latitude))")
        let coordinateSpan = MKCoordinateSpan(latitudeDelta: 20, longitudeDelta: 20)
        _ = MKCoordinateRegion(center: location.coordinate, span: coordinateSpan)
        // mapView.centerCoordinate = location.coordinate
        //mapView.setRegion(coordinateRegion, animated: true)
        if(i1 != 0){
            self.sortByDistance()
        }

    }

0 个答案:

没有答案