In your Appdelegate.h
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate,CLLocationManagerDelegate>
{
CLLocationCoordinate2D homeLocation;
CLLocationCoordinate2D phoneLocation;
CLLocationManager *locationManager;
CLLocation *currentLocation;
NSDictionary *cstreampostData;
}
In Appdeleate.m
-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
if ([CLLocationManager locationServicesEnabled]) {
self.locationManager = [[CLLocationManager alloc]init];
self.locationManager.delegate=self;
self.locationManager.desiredAccuracy=kCLLocationAccuracyKilometer;
}else{
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Location Services Not Available!" message:@"" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles: nil];
[alert show];
}
.
.
.
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
[self.window makeKeyAndVisible];
return YES;
}
#pragma mark- Current Location Delegates
-(void)setUpLocationManager:(id)sender{
//location tracking
[self.locationManager startUpdatingLocation];
}
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
self.phoneLocation=CLLocationCoordinate2DMake(newLocation.coordinate.latitude, newLocation.coordinate.longitude);
self.currentLocation=newLocation;
if (newLocation.horizontalAccuracy <=1000.0f) {
[self.locationManager stopUpdatingLocation];
NSLog(@"%g %g",newLocation.coordinate.longitude, newLocation.coordinate.latitude);
self.cstreampostData=[NSDictionary dictionaryWithObjectsAndKeys:
[NSString stringWithFormat:@"%g",newLocation.coordinate.latitude],@"latitude",
[NSString stringWithFormat:@"%g",newLocation.coordinate.longitude],@"longitude", nil];
}
NSLog(@"current location latitude is======%f",phoneLocation.latitude);
NSLog(@"current location longitude is======%f",phoneLocation.longitude);
}
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
if (error.code == kCLErrorDenied) {
[self.locationManager stopUpdatingLocation];
}else if(error.code == kCLErrorLocationUnknown){
//retry
}else{
}
NSLog(@"%@",error);
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Location Services Not Available!" message:@"" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles: nil];
[alert show];
}
in your ViewController.m
-(void)viewDidLoad
{
[super viewDidLoad];
AppDelegate *appDelegate=(AppDelegate *)[UIApplication sharedApplication].delegate;
[appDelegate setUpLocationManager:sender];
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…