How to fetch current location in appdelegate using swift

余生长醉 提交于 2019-12-04 21:11:42
// Just call setupLocationManager() in didFinishLaunchingWithOption.

    func setupLocationManager(){
            locationManager = CLLocationManager()
            locationManager?.delegate = self
            self.locationManager?.requestAlwaysAuthorization()
            locationManager?.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
            locationManager?.startUpdatingLocation()

        }

    // Below method will provide you current location.
     func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

            if currentLocation == nil {
                currentLocation = locations.last
                locationManager?.stopMonitoringSignificantLocationChanges()
                let locationValue:CLLocationCoordinate2D = manager.location!.coordinate

                print("locations = \(locationValue)")

                locationManager?.stopUpdatingLocation()
            }
        }

    // Below Mehtod will print error if not able to update location.
        func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
            print("Error")
        }

By the following code you can get name of location and it's longitude and latitude

extension AppDelegate :  CLLocationManagerDelegate
{

    func geocode(latitude: Double, longitude: Double, completion: @escaping (CLPlacemark?, Error?) -> ())  {
        CLGeocoder().reverseGeocodeLocation(CLLocation(latitude: latitude, longitude: longitude)) { completion($0?.first, $1) }
    }

    // Below Mehtod will print error if not able to update location.
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print("Error Location")
    }


    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        //Access the last object from locations to get perfect current location
        if let location = locations.last {

            let myLocation = CLLocationCoordinate2DMake(location.coordinate.latitude,location.coordinate.longitude)

            geocode(latitude: myLocation.latitude, longitude: myLocation.longitude) { placemark, error in
                guard let placemark = placemark, error == nil else { return }
                // you should always update your UI in the main thread
                DispatchQueue.main.async {
                    //  update UI here
                    print("address1:", placemark.thoroughfare ?? "")
                    print("address2:", placemark.subThoroughfare ?? "")
                    print("city:",     placemark.locality ?? "")
                    print("state:",    placemark.administrativeArea ?? "")
                    print("zip code:", placemark.postalCode ?? "")
                    print("country:",  placemark.country ?? "")
                }
            }
        }
        manager.stopUpdatingLocation()

    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!