I’ve been tackling this for a while, and I need some help designing my logic.
I want to do three things in this order
1) Get the user’s location
2) Call a web service with that user’s location
3) load the user interface with results
I want this to be designed in a way that makes it simple for me to refresh the results, so if the user presses a refresh button, I do steps 1-3 again.
Right now, I do it as follows. This is my code in my ViewController.
- (void) viewDidLoad {
//initialize CLLocationManager
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.delegate = self;
[self.locationManager startUpdatingLocation];
- (void) locationManager: (CLLocationManager *)manager
didUpdateToLocation: (CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
if (oldLocation!= nil) { // make sure to wait until second latlong value
[self setLatitude:newLocation.coordinate.latitude];
[self setLongitude: newLocation.coordinate.longitude];
[self.locationManager stopUpdatingLocation];
self.locationManager.delegate = nil;
[self makeUseOfLocationWithLat:[self getLatitude] andLon:[self getLongitude]];
}
- (void) makeUseOfLocationWithLat: (double) lat andLon: (double) lon {
// call web service
[self loadUI];
}
- (void) loadUI {
// loads the user interface
}
Correct me if I’m wrong, but my design is really bad. It’s not modular at all, each method is tied to each other. Also, I’m doing intensive web service calls in my ViewController, as opposed to in any model classes. How do you set this up properly? One of the major issues I have is… I don’t know when my latitude and longitude variables get their values. If I don’t call makeUseOfLocation from my delegate method, then I end up calling makeUseOfLocation with nil values of latitude and longitude.
I’ve looked into singletons for my location managing, NSKeyValueObserving Protocols, dispatch_queues, NSOperations, but I’m new to developing on iOS, and I’m getting stuck somewhere with whatever I try. Please let me know your thoughts on how to set this up.
Thanks for your time, I really appreciate it.
If you really want to separate it, as an easy first step, I would do the following:
This creates a small protocol between your location tracking class and the controller. The NSNotification docs are pretty good, they’ll get you there.
You could have the controller own the instance, or the application delegate. I don’t think a singleton is really all that necessary.
You could also use key-value observing, or a protocol/delegate type setup, any of them will work as they’re all basically the same pattern (Observer).