1

swift newbie here. I am trying to get my simple core location app retrieve data automatically after getting coordinates by locationManager. I have implemented separate class not to make my main view controller be responsible for too many tasks here how it looks like:

import Foundation
import CoreLocation

class CoreLocationController : NSObject, CLLocationManagerDelegate {

var locationManager = CLLocationManager()

var lastCoordinates: (lat: Double, lon: Double)?

override init() {  
    super.init()
    self.locationManager.delegate = self
    self.locationManager.requestWhenInUseAuthorization()
    self.locationManager.distanceFilter  = 3000
    self.locationManager.desiredAccuracy = kCLLocationAccuracyKilometer

}

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

    let location = locations.last! as CLLocation

    self.lastCoordinates = (location.coordinate.latitude, location.coordinate.longitude)
    print("didUpdateLocations:  \(location.coordinate.latitude), \(location.coordinate.longitude)")

}

func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
    print("didChangeAuthorizationStatus")

    switch status {
    case .NotDetermined:
        print(".NotDetermined")
        break

    case .AuthorizedWhenInUse:
        print(".AuthorizedWhenInUse")
        self.locationManager.startUpdatingLocation()
        break

    case .Denied:
        print(".Denied")
        break

    default:
        print("Unhandled authorization status")
        break

    }
}

func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
   }
}

Of course i have initialized it in AppDelegate.swift

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?

var coreLocationController: CoreLocationController?

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    self.coreLocationController = CoreLocationController()
    return true
}

Now my main ViewController after clicking button is performing retrieveWeatherForecast with appDelegate passed to it to get reference to CoreLocationController.lastCoordinates property. I came to conclusion that in order to perform retrieveWeatherForecast after getting coordinates immediate after launching the best way will be to run this method inside locationManager func (the one with didUpdateLocations argument). In order to do it i will need to have reference to ViewController running instance to perform sth like:

runningViewControlerinstance.retrieveWeatherForecast(runningViewControlerinstance.appDel)

main ViewController code:

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var currentTemperatureLabel: UILabel?
@IBOutlet weak var currentHumidityLabel: UILabel?
@IBOutlet weak var currentPrecipitationLabel: UILabel?
@IBOutlet weak var currentWeatherIcon: UIImageView?
@IBOutlet weak var currentWeatherSummary: UILabel?
@IBOutlet weak var refreshButton: UIButton?
@IBOutlet weak var activityIndicator: UIActivityIndicatorView?

let appDel = UIApplication.sharedApplication().delegate! as! AppDelegate

private var forecastAPIKey: String?

override func viewDidLoad() {
    super.viewDidLoad()

    let path = NSBundle.mainBundle().pathForResource("APIkeys", ofType: "plist")
    let dict = NSDictionary(contentsOfFile: path!)

    self.forecastAPIKey = dict!.objectForKey("forecastAPIKey") as? String

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

func retrieveWeatherForecast(appDel: AppDelegate ) {
    let currentCoordinates :(lat: Double, lon: Double) =  (appDel.coreLocationController?.lastCoordinates)!

    let forecastService = ForecastService(APIKey: forecastAPIKey!)
    forecastService.getForecast(currentCoordinates.lat, lon: currentCoordinates.lon) {
        (let currently) in

        if let currentWeather = currently {

            dispatch_async(dispatch_get_main_queue()) {

                if let temperature = currentWeather.temperature {
                    self.currentTemperatureLabel?.text = "\(temperature)º"
                }

                if let humidity = currentWeather.humidity {
                    self.currentHumidityLabel?.text = "\(humidity)%"
                }

                if let precipitation = currentWeather.precipProbability {
                    self.currentPrecipitationLabel?.text = "\(precipitation)%"
                }

                if let icon = currentWeather.icon {
                    self.currentWeatherIcon?.image = icon
                }

                if let summary = currentWeather.summary {
                    self.currentWeatherSummary?.text = summary
                }

                self.toggleRefreshAnimation(false)

            }


        }
    }
}

@IBAction func refreshWeather() {
    toggleRefreshAnimation(true)
    retrieveWeatherForecast(appDel)
}

func toggleRefreshAnimation(on: Bool) {
    refreshButton?.hidden = on
    if on {
        activityIndicator?.startAnimating()
    } else {
        activityIndicator?.stopAnimating()
    }
 }
}

I will appreciate very much any help, comments and suggestions from you the swift community, Thanks!

2 Answers 2

0

If you have a separate class handling the location services (which is a good design pattern) or alternatively the app delegate, the best way to notify any active view controllers is via NSNotification.

Register in the view controller via NSNotificationCenter in viewDidAppear and remove yourself as an observer in viewWillDisappear. There is plenty of documentation to explain the details.

This loose coupling of controllers to asynchronous processes is much safer than keeping references to UI objects.

-1

"Of course i have initialized it in AppDelegate.swift" Why? There is no reason to initialise it there, is there? Initialise it where you intend to use it. You viewController needs access to your CoreLocationController to use, display or edit locations. So initialise and use it there and you won't have to pass your view controller to your location manager.

2
  • That might lead to multiple core location controllers. A singleton pattern is clearly preferable here.
    – Mundi
    Nov 14, 2015 at 12:53
  • Ok. Since it's swift, declaring a static variable (which is also a lazy variable) in the CoreLocationController is also possible.
    – user965972
    Nov 14, 2015 at 12:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.