0

What I'm trying to accomplish is, getting the user's coordination and city at app launch, once the app is in foreground, there is a label display the city.
I'm using the following code to get such information.
When I call the location service from a UIButton after the app launch, everything works as it should. Now my questions are,
1. where I should put the code, to get this data at app launch?
2. is there anything else I should implement? or be aware of?
Thank you all in advance.

import Foundation
import CoreLocation
import AddressBookUI

protocol ParseCityDelegate {
     func populateCurrentCity(city: Locations)
}

class GeoServices: UIViewController, CLLocationManagerDelegate {

var lati = Double()
var long = Double()
let locationManager = CLLocationManager()
var parseLocationDelegate: ParseCityDelegate?
let fetchWeatherData = RequestData()

// Location services
func startUpdateLocation() {
    // Ask for user authorization when getting location
    self.locationManager.requestAlwaysAuthorization()
    self.locationManager.requestWhenInUseAuthorization()

    if CLLocationManager.locationServicesEnabled() {
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
        locationManager.startUpdatingLocation()
    }
}

// Retrive Geo Coordination
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let currentCoordination = locationManager.location?.coordinate
    lati = currentCoordination!.latitude
    long = currentCoordination!.longitude
    reverseGeocoding(latitude: lati, longitude: long)
    // Stop update location
    locationManager.stopUpdatingLocation()
}

// Retrive City from coordination
func reverseGeocoding(latitude: CLLocationDegrees, longitude: CLLocationDegrees) {
    let location = CLLocation(latitude: lati, longitude: long)
    CLGeocoder().reverseGeocodeLocation(location, completionHandler: {(placemarks, error) -> Void in
        if error != nil {
            print(error!)
            // Display error message
            let alert = UIAlertController(title: "", message: "Unable to locate your coordination.", preferredStyle: .alert)
            let cancel = UIAlertAction(title: "OK", style: .cancel, handler: nil)
            alert.addAction(cancel)
            self.present(alert, animated: true, completion: nil)
            return
        }
        else if (placemarks?.count)! > 0 {
            let pm = placemarks![0] as CLPlacemark
            let cityName = Locations(City: pm.locality!)

            if self.parseLocationDelegate != nil {
                DispatchQueue.main.async(execute: { () -> Void in
                    self.parseLocationDelegate?.populateCurrentCity(city: cityName)
                })
            }
        }
    })
}
}
f_qi
  • 689
  • 8
  • 21

0 Answers0