Advertisement
Guest User

What's the easiest way to get the current location of an iPhone

a guest
Feb 26th, 2012
36
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.18 KB | None | 0 0
  1. #import <CoreLocation/CoreLocation.h>
  2. #import <Foundation/Foundation.h>
  3.  
  4. @interface LocationController : NSObject <CLLocationManagerDelegate> {
  5. CLLocationManager *locationManager;
  6. CLLocation *currentLocation;
  7. }
  8.  
  9. + (LocationController *)sharedInstance;
  10.  
  11. -(void) start;
  12. -(void) stop;
  13. -(BOOL) locationKnown;
  14.  
  15. @property (nonatomic, retain) CLLocation *currentLocation;
  16.  
  17. @end
  18. @implementation LocationController
  19.  
  20. @synthesize currentLocation;
  21.  
  22. static LocationController *sharedInstance;
  23.  
  24. + (LocationController *)sharedInstance {
  25. @synchronized(self) {
  26. if (!sharedInstance)
  27. sharedInstance=[[LocationController alloc] init];
  28. }
  29. return sharedInstance;
  30. }
  31.  
  32. +(id)alloc {
  33. @synchronized(self) {
  34. NSAssert(sharedInstance == nil, @"Attempted to allocate a second instance of a singleton LocationController.");
  35. sharedInstance = [super alloc];
  36. }
  37. return sharedInstance;
  38. }
  39.  
  40. -(id) init {
  41. if (self = [super init]) {
  42. self.currentLocation = [[CLLocation alloc] init];
  43. locationManager = [[CLLocationManager alloc] init];
  44. locationManager.delegate = self;
  45. [self start];
  46. }
  47. return self;
  48. }
  49.  
  50. -(void) start {
  51. [locationManager startUpdatingLocation];
  52. }
  53.  
  54. -(void) stop {
  55. [locationManager stopUpdatingLocation];
  56. }
  57.  
  58. -(BOOL) locationKnown {
  59. if (round(currentLocation.speed) == -1) return NO; else return YES;
  60. }
  61.  
  62. - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
  63. //if the time interval returned from core location is more than two minutes we ignore it because it might be from an old session
  64. if ( abs([newLocation.timestamp timeIntervalSinceDate: [NSDate date]]) < 120) {
  65. self.currentLocation = newLocation;
  66. }
  67. }
  68.  
  69. - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
  70. UIAlertView *alert;
  71. alert = [[UIAlertView alloc] initWithTitle:@"Error" message:[error description] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
  72. [alert show];
  73. [alert release];
  74. }
  75.  
  76. -(void) dealloc {
  77. [locationManager release];
  78. [currentLocation release];
  79. [super dealloc];
  80. }
  81.  
  82. @end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement