I want to use the following code to find a user’s location in multiple parts of my app. To avoid complexity, I only want to have one place where I get the user’s location. I would assume that I need to put it in my appDelegate and then call it somehow from the other views when I need to use it. Does anyone know what I would need to use to get the location as an NSString on the views/tabs other than my appDelegate? Thank you!
- (NSString *)deviceLocation {
NSString *theLocation = [NSString stringWithFormat:@"latitude: %f longitude: %f",
locationManager.location.coordinate.latitude,
locationManager.location.coordinate.longitude];
return theLocation;
}
- (void)viewDidLoad
{
locationManager = [[CLLocationManager alloc] init];
locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
[locationManager startUpdatingLocation];
}
Move all of your location listener and related stuff to the app delegate, and then make
NSString *locationproperty ofAppDelegate, now whenever you get an updated location set that toNSString *location, in your otherViewControllers, when you need, access the app delegate’s location property.If you really need an updated location you can use NSNotificationCenter and broadcast a notification about new location update, so the
ViewControllerwhich really need an updated location will register itself for Notification about new location and will do stuff accordingly.