Как использовать местоположение пользователя вне функции locationmanager swift 3

Я немного новичок в кодировании и придумал эту проблему. Я делаю приложение trashcanfinder на основе MapKit, и я хотел бы показать расстояние от местоположения пользователя до моих выводов на карте. Я уже сделал свою функцию для преобразования CLLocationCoordinate2D в CLLocation, и у меня есть функция для отображения расстояния от одной точки до другой, но я не могу использовать местоположение пользователя вне функции locationmanager.

Это мой код:

 @IBOutlet weak var mapView: MKMapView!

let manager = CLLocationManager()


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

    let location = locations[0]
    let span:MKCoordinateSpan = MKCoordinateSpanMake(0.01, 0.01)
    let myLocation = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
    let region:MKCoordinateRegion = MKCoordinateRegionMake(myLocation, span)

    mapView.setRegion(region, animated: true)

    self.mapView.showsUserLocation = true


}



    func distancePointToPoint(location1: CLLocationCoordinate2D, location2: CLLocationCoordinate2D) -> String {
        let cllocation1 = converter(location: location1)
        let cllocation2 = converter(location: location2)
        let distance = cllocation1.distance(from: cllocation2)
        let shortDistance = distance - distance.truncatingRemainder(dividingBy: 0.1)                                   //makes sure there is only one number behind comma
        if shortDistance < 0 {
            return "The distance is \(shortDistance) meters"
        }
        else {
            return "The distance is \(shortDistance - (shortDistance / 1000).truncatingRemainder(dividingBy: 0.1)) kilometers"
        }
    }

Поэтому мне нужно использовать местоположение пользователя как location1 в функции distancePointToPoint.

Я знаю, что с любой другой функцией я мог бы просто вернуть значение, но у меня нет никаких значений, чтобы дать функцию locationmanager, поскольку она получит ее от самого устройства.

Я уже провел исследование, и единственный другой способ, который я нашел, - это поместить переменную myLocation за пределы функции и изменить только значение внутри функции, но xcode начинает жаловаться, что у класса нет инициализатора, и я не не знаю что делать

Извините, если я сделал какие-то глупые ошибки, так как я только начал изучать код.

Любая помощь приветствуется!

1 ответ

Решение

Здесь LocationManager didUpdate Методы :

//MARK: LocationManager Delegates Methods
  func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        //Get Current Location
        let location = locations.last! as CLLocation
        let userLocation:CLLocation = locations[0] as CLLocation

        //Save current lat long
        UserDefaults.standard.set(userLocation.coordinate.latitude, forKey: "LAT")
        UserDefaults.standard.set(userLocation.coordinate.longitude, forKey: "LON")
        UserDefaults().synchronize()
    }

А затем создайте функцию, которая вызывается из метода viewWillAppear:

     func createPin(){

            //Access user Location LAT & LON from User Defaults
            let coordinate =  CLLocationCoordinate2D(latitude: UserDefaults.standard.value(forKey: "LAT") as! CLLocationDegrees, longitude: UserDefaults.standard.value(forKey: "LON") as! CLLocationDegrees)
        var region = MKCoordinateRegion(center: coordinate, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
        region.center = coordinate
        self.map.setRegion(region, animated: true)

//Also now you have coordintes know for USER Location you can add annotation too

    //Rest do your stuff 
    }

Не стесняйтесь комментировать, если какие-либо вопросы. Спасибо

Другие вопросы по тегам