后台定位

#import "LocationsAppDelegate.h"
#import "RootViewController.h"
 
@implementation LocationsAppDelegate
@synthesize window;
@synthesize navigationController;
 
-(void)initLocationManager {                         #1
     if (locationManager == nil) {
          locationManager = [[CLLocationManager alloc] init];
          locationManager.delegate = self;
          [locationManager startMonitoringSignificantLocationChanges];
     }
}
- (void)saveCurrentData:(NSString *)newData {               #2
     NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
     NSMutableArray *savedData = [[NSMutableArray alloc] initWithArray:[defaults objectForKey:@"kLocationData"]];
     [savedData addObject:newData];
     [defaults setObject:savedData forKey:@"kLocationData"];
     [savedData release];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions      
{ 
  if (![CLLocationManager significantLocationChangeMonitoringAvailable]) #3 
{UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Sorry" message:@"Your device won't support the significant location change." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
          [alert show];
          [alert release];
          return YES;                                   #3
     }                                             #3
     [self initLocationManager];
    [self.window addSubview:navigationController.view];
    [self.window makeKeyAndVisible];
    return YES;
}
 
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {                                        #4
     NSString *locationData = [NSString stringWithFormat:@"%.6f, %.6f",newLocation.coordinate.latitude, newLocation.coordinate.longitude];
     [self saveCurrentData:locationData];
}                                                  #4
 
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {                         #5
     NSString *errorData = [NSString stringWithFormat:@"%@",[error localizedDescription]];
     NSLog(@"%@", errorData);                              #5
}
- (void)dealloc {
     [[NSNotificationCenter defaultCenter] removeObserver:self];
[locationManager release];
    [navigationControllerrelease];
    [window release];
    [super dealloc];
}

@end
原文地址:https://www.cnblogs.com/chenfulai/p/2514409.html