Reputation: 3682
In iOS, I have declared the CLLocationManager variable like this:
DashBoardViewController.h
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
@class AppDelegate;
@interface DashBoardViewController : UIViewController<CLLocationManagerDelegate, UIAlertViewDelegate>{
AppDelegate *appDel;
}
@property(nonatomic,strong) CLLocationManager *locationManager;
@property (nonatomic,retain) CLLocation *current;
-(void)localnotification;
@end
And in the DashBoardViewController.m file:
#import "DashBoardViewController.h"
#import "AppDelegate.h"
#define IS_OS_8_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
@interface DashBoardViewController ()
@end
@implementation DashBoardViewController
@synthesize current,locationManager;
- (void)viewDidLoad
{
[super viewDidLoad];
appDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
[self localnotification];
}
-(void)localnotification{
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
if(IS_OS_8_OR_LATER) {
[locationManager requestAlwaysAuthorization];
}
[locationManager startMonitoringSignificantLocationChanges];
}
I also Implemented
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
//some code
}
Now I'm accessing the "locationManager" and "localnotification" method like this in SettingsViewController.m
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#import "DashBoardViewController.h"
//To stop the Location Manager service
- (IBAction)stopButtonAction:(id)sender {
DashBoardViewController *dash=[[DashBoardViewController alloc] init];
dash.locationManager=nil;
}
//To start the Location Manager service
- (IBAction)startButtonAction:(id)sender {
DashBoardViewController *dash=[[DashBoardViewController alloc] init];
[dash localnotification];
}
But it's not working. All time locationManager returning null. What's wrong in this code?
Upvotes: 2
Views: 611
Reputation: 842
When you
DashBoardViewController *dash=[[DashBoardViewController alloc] init];
it creates a new DashBoardViewController
instance. You can define locationManager
in AppDelegate
and access directly to it from anywhere in your code.
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
appDelegate.locationManager = nil;
Upvotes: 3
Reputation: 375
viewDidLoad is not called when you alloc-init the view controller. It is called when loading the view which is done later when you actually show it. That is why it is nil. I would suggest to create the location manager in the AppDelegate if you want to access it across multiple view controllers.
Upvotes: 3