3

So I am saving the users location on a button push in a NSUserDefault. But When I call it I get null.

The goal is to get the users location(done) and then save it so when the map is reloaded the pin shows back up where the user once was. Right now it clears and resets the map.

Saving on button push:

 MKCoordinateRegion location1;
 location1.center.latitude =locationManager.location.coordinate.latitude;
 location1.center.longitude= locationManager.location.coordinate.longitude;
 location1.span.longitudeDelta=0.1;
 location1.span.latitudeDelta =0.1;

 MapAnnotation *ann1 =[[MapAnnotation alloc] init];
 ann1.title=@"You Parked Here";
 ann1.subtitle=@"";
 ann1.coordinate= location1.center;
 [mapView addAnnotation:ann1];

 NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
 [ud setDouble:location1.center.latitude forKey:@"savedCoordinate-latitude"];
 [ud setDouble:location1.center.longitude forKey:@"savedCoordinate-longitude"];
 [ud setBool:YES forKey:@"savedCoordinate-exists"];
 [ud synchronize]; 

Recalling in viewWillAppear:

 -(void)viewWillAppear:(BOOL)animated{

NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
if ([ud boolForKey:@"savedCoordinate-exists"])
{
    CLLocationCoordinate2D savedCoordinate;
    savedCoordinate.latitude = [ud doubleForKey:@"savedCoordinate-latitude"];
    savedCoordinate.longitude = [ud doubleForKey:@"savedCoordinate-longitude"];
    //create annotation object using savedCoordinate and add to map view...
    NSLog(@"%@",savedCoordinate.latitude);

    MKCoordinateRegion location1;
    //location1.center.latitude =savedCoordinate.latitude;
    //location1.center.longitude= savedCoordinate.longitude;
    location1.span.longitudeDelta=0.1;
    location1.span.latitudeDelta =0.1;

    MapAnnotation *ann1 =[[MapAnnotation alloc] init];
    ann1.title=@"You Parked Here";
    ann1.subtitle=@"";
    ann1.coordinate= savedCoordinate;
    [mapView addAnnotation:ann1];
 }  

}

Full .m page:

 #import "LocationTestViewController.h"
 #import "CoreLocation/CoreLocation.h"
 #import "MapAnnotation.h"

 @implementation LocationTestViewController
 @synthesize locationManager;
 @synthesize mapView;
 @synthesize labelText;

 - (void)dealloc
 {
  [mapView release];
  [locationManager release];
  [super dealloc];
 }

 - (void)didReceiveMemoryWarning
{
  // Releases the view if it doesn't have a superview.
  [super didReceiveMemoryWarning];

  // Release any cached data, images, etc that aren't in use.
 }

 #pragma mark - View lifecycle

 /*
 // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
 - (void)viewDidLoad
 {
    [super viewDidLoad];

 }*/
 -(void)viewWillAppear:(BOOL)animated{

   NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
   if ([ud boolForKey:@"savedCoordinate-exists"])
    {
      CLLocationCoordinate2D savedCoordinate;
      savedCoordinate.latitude = [ud doubleForKey:@"savedCoordinate-latitude"];
      savedCoordinate.longitude = [ud doubleForKey:@"savedCoordinate-longitude"];
      //create annotation object using savedCoordinate and add to map view...
      NSLog(@"%f",savedCoordinate.latitude);

      MKCoordinateRegion location1;
      //location1.center.latitude =savedCoordinate.latitude;
      //location1.center.longitude= savedCoordinate.longitude;
      location1.span.longitudeDelta=0.1;
      location1.span.latitudeDelta =0.1;

      MapAnnotation *ann1 =[[MapAnnotation alloc] init];
      ann1.title=@"You Parked Here";
      ann1.subtitle=@"";
      ann1.coordinate= savedCoordinate;
      [mapView addAnnotation:ann1];
   }  

 }

 - (void)viewDidUnload
 {
   [self setMapView:nil];
   [self setLocationManager:nil];
   [super viewDidUnload];
   // Release any retained subviews of the main view.
   // e.g. self.myOutlet = nil;
 }

 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
 {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
  }

 - (IBAction)getLocation:(id)sender {

    locationManager = [[CLLocationManager alloc] init];
    locationManager.distanceFilter=kCLDistanceFilterNone;
    locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
    [locationManager startUpdatingLocation];

    [mapView setMapType:MKMapTypeStandard];
    [mapView setZoomEnabled:YES];
    [mapView setScrollEnabled:YES];
    MKCoordinateRegion region = {{0.0,0.0},{0.0,0.0}};
    region.center.latitude = locationManager.location.coordinate.latitude;
    region.center.longitude = locationManager.location.coordinate.longitude;
    region.span.longitudeDelta = 0.005f;
    region.span.latitudeDelta = 0.005f;
    [mapView setRegion:region animated:YES];
    [mapView setDelegate:sender];



    MKCoordinateRegion location1;
   location1.center.latitude =locationManager.location.coordinate.latitude;
   location1.center.longitude= locationManager.location.coordinate.longitude;
   location1.span.longitudeDelta=0.1;
   location1.span.latitudeDelta =0.1;

   labelText.text = [NSString stringWithFormat:@"LATITUDE: %f", location1.center.latitude];

   NSLog(@"button b4 save: %@", [NSString stringWithFormat:@"LATITUDE: %f", locationManager.location.coordinate.latitude]);

   MapAnnotation *ann1 =[[MapAnnotation alloc] init];
   ann1.title=@"You Parked Here";
   ann1.subtitle=@"";
   ann1.coordinate= location1.center;
   [mapView addAnnotation:ann1];

   NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
   [ud setDouble:location1.center.latitude forKey:@"savedCoordinate-latitude"];
   [ud setDouble:location1.center.longitude forKey:@"savedCoordinate-longitude"];
   [ud setBool:YES forKey:@"savedCoordinate-exists"];
   [ud synchronize]; 

   CLLocationCoordinate2D savedCoordinate;
   savedCoordinate.latitude = [ud doubleForKey:@"savedCoordinate-latitude"];
   savedCoordinate.longitude = [ud doubleForKey:@"savedCoordinate-longitude"];
   //create annotation object using savedCoordinate and add to map view...
   NSLog(@"button push, %f",savedCoordinate.latitude);
 }

 - (IBAction)clearPins:(id)sender{
    NSArray *annotations = [mapView annotations];
    for (id annotation in annotations)
 {
       if ([annotation isKindOfClass:[MKUserLocation class]])
       {
          continue;
       }
       [mapView removeAnnotation:annotation];
    }   

 } 

 -(IBAction)goMainMenu{
    [self.parentViewController dismissModalViewControllerAnimated:YES];
 }
 @end

EDIT SOLUTION:

I added this to my button method:

 CLLocation *userLoc = mapView.userLocation.location;
 CLLocationCoordinate2D userCoordinate = userLoc.coordinate;

 NSLog(@"user latitude = %f",userCoordinate.latitude);
 NSLog(@"user longitude = %f",userCoordinate.longitude);

 NSUserDefaults *gLat = [NSUserDefaults standardUserDefaults];
 [gLat setFloat:userCoordinate.latitude forKey:@"latNumber"];

 NSUserDefaults *gLong = [NSUserDefaults standardUserDefaults];
 [gLong setFloat:userCoordinate.longitude forKey:@"longNumber"];


 float myLat=[gLat floatForKey:@"latNumber"];
 NSLog(@"Button Push: lat : %f",myLat);

 float myLong=[gLong floatForKey:@"longNumber"];
 NSLog(@"Button Push: long : %f",myLong);  

May not be the cleanest thing but it gets the job done.

Rick
  • 1,123
  • 1
  • 18
  • 36
  • NSLog(@"%@",savedCoordinate.latitude); seems nslog will work incorrect – NeverBe Feb 13 '12 at 22:21
  • Have you logged the values that you're saving? Are they correct? What comes back out of userDefaults- is that correct? What is MapAnnotation? – Rayfleck Feb 13 '12 at 22:31
  • hmmm I seem to be getting null or 0; How can i pull my coords out? I will post more code. – Rick Feb 14 '12 at 13:58
  • In the `getLocation:` method, what do all the NSLogs say? You can't/shouldn't read the location immediately after calling startUpdatingLocation (it will be zero or unreliable). You should read/save the location (and create the annotation) in the didUpdateToLocation delegate method. –  Feb 14 '12 at 14:25
  • Well see the getLocation is a button push. It starts out a full size map and then zooms to the users location. The problem is the logs don't work. Or I should say I am failing at getting the coords to show in a NSLog. I believe I need help pulling out the coords. – Rick Feb 14 '12 at 14:51
  • What does the last NSLog in getLocation ("button push") print exactly? Does the app get to that line? –  Feb 14 '12 at 15:20
  • Yes it gets to that line and my red pin does show my current spot on top of my blue location, so I know its getting the coords. As for the last NSLog it shows "button push, 0.000000" . – Rick Feb 14 '12 at 15:39
  • Does "button b4 save" say the same thing (0.0)? As I said, you can't read the location coordinates immediately after calling startUpdatingLocation. The location won't be determined so quickly. You have to read the location in didUpdateToLocation. –  Feb 14 '12 at 16:32
  • Ok I got it. @Anna I will have to test to see how accurate it is. If I revise it like you suggest I'll update this post. Thanks – Rick Feb 14 '12 at 18:22

1 Answers1

2

The %@ string format specifier is for Objective-C objects and can't be used with floats. Try using the %f operator like this:

NSLog(@"latitude is %f", savedCoordinate.latitude);

Here's Apple's documentation on String Format Specifiers.

Zev Eisenberg
  • 7,836
  • 5
  • 31
  • 74
  • I noticed that using a `float` with coordinates truncates the last few digits (or rounds them up)... is there any other number variable that can be used to store more values of the coordinate? – Sam Spencer Mar 10 '13 at 15:32
  • I don’t know the specifics, so I will refer you to [this answer](http://stackoverflow.com/a/1074537/255489). – Zev Eisenberg Mar 11 '13 at 16:40