2012-02-13 3 views
3

Так что я сохраняю местоположение пользователей при нажатии кнопки в NSUserDefault. Но когда я это называю, я получаю нуль.Сохранение и вызов пользовательских соглашений с NSUserDefaults

Цель состоит в том, чтобы получить местоположение пользователя (сделано), а затем сохранить его, поэтому, когда карта перезагружается, вывод показывает резервную копию, где был один пользователь. Сейчас он очищает и сбрасывает карту.

Экономия кнопки:

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]; 
[email protected]"You Parked Here"; 
[email protected]""; 
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]; 

ссылаясь на 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]; 
    [email protected]"You Parked Here"; 
    [email protected]""; 
    ann1.coordinate= savedCoordinate; 
    [mapView addAnnotation:ann1]; 
} 

} 

Полный .m страница:

#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]; 
     [email protected]"You Parked Here"; 
     [email protected]""; 
     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]; 
    [email protected]"You Parked Here"; 
    [email protected]""; 
    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 РЕШЕНИЕ:

Я добавил это моя кнопка metho d:

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); 

Может быть, не самая чистая вещь, но она выполняет свою работу.

+0

NSLog (@ "% @", savedCoordinate.latitude); похоже, что nslog будет работать некорректно – NeverBe

+0

Вы зарегистрировали значения, которые вы сохраняете? Правильны ли они? Что происходит из userDefaults - это правильно? Что такое MapAnnotation? – Rayfleck

+0

hmmm Кажется, я получаю null или 0; Как я могу вытащить свои койки? Я напишу больше кода. – Rick

ответ

2

Спецификатор формата строки %@ предназначен для объектов Objective-C и не может использоваться с поплавками. Попробуйте использовать оператор %f так:

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

Вот документация Apple, на String Format Specifiers.

+0

Я заметил, что использование 'float' с координатами обрезает последние несколько цифр (или округляет их) ... есть ли какая-либо другая числовая переменная, которая может использоваться для хранения большего количества координат? –

+0

Я не знаю специфики, поэтому я передам вам [этот ответ] (http://stackoverflow.com/a/1074537/255489). –

Смежные вопросы