2014-12-26 2 views
0

Я просто играю с классом CLLocation. Я успешно выполнил приведенный ниже код. Когда я нажимаю кнопку, он отображает местоположение в ALert msg. Когда я снова нажимаю на ту же кнопку, местоположение отображается неправильно. А также я отметил, что в eveytime мне нужно перейти в настройку «Конфиденциальность», чтобы предоставлять доступ всегда каждый раз. Когда приложение действительно показывает текущее местоположение, доступ к местоположению в настройке iPhone переходит в состояние «Пусто». снова я должен установить его для Всегда, чтобы запустить приложение. Я ничего не добавил в .plists. Я написал только код ниже. Моя проблема Это показывает правильное расположение только в первый раз после установки местоположения accress ВсегдаРасположение отображается один раз

-(CLLocationCoordinate2D) getLocation{ 
     CLLocationCoordinate2D coordinate; 


     if ([CLLocationManager locationServicesEnabled]) 
     { 


     CLLocationManager *locationManager = [[CLLocationManager alloc] init]; 
     locationManager.delegate = self; 
     locationManager.desiredAccuracy = kCLLocationAccuracyBest; 
     locationManager.distanceFilter = kCLDistanceFilterNone; 
      [locationManager requestWhenInUseAuthorization]; 
     [locationManager startUpdatingLocation]; 



     CLLocation *location = [locationManager location]; 
     coordinate = [location coordinate]; 
     } 
      return coordinate; 

    } 


    - (void)startTimer { 

     // if ([Run isEqualToString:@"can"]) { 

      i++; 

      NSLog(@"the i value %d", i); 

      Run [email protected]"cant"; 
     CLLocationCoordinate2D coordinate = [self getLocation]; 

     CLGeocoder *ceo = [[CLGeocoder alloc]init]; 
     CLLocation *loc = [[CLLocation alloc]initWithLatitude:coordinate.latitude longitude:coordinate.longitude]; //insert your coordinates 

     [ceo reverseGeocodeLocation:loc 
        completionHandler:^(NSArray placemarks, NSError error) 
     { 
      CLPlacemark *placemark = [placemarks objectAtIndex:0]; 

      NSDictionary *eventLocation = [NSDictionary dictionaryWithObjectsAndKeys:placemark.name,@"NAME",placemark.subLocality,@"SUBLOCALITY" ,placemark.postalCode,@"POSTALCODE" ,nil]; 

      LocationDetails= [NSMutableDictionary dictionaryWithObjectsAndKeys:eventLocation,@"value", nil]; 


      NSString *name=placemark.name; 
      NSString *subLocality=placemark.subLocality; 
      NSString *postalCode=placemark.postalCode; 



      NSMutableArray *listData; 
      if (!listData) listData = [[NSMutableArray alloc] init]; 
      [listData addObject:LocationDetails]; 

      NSLog(@"the Location details %@", listData); 

      NSString *location=[NSString stringWithFormat:@"You are now in %@ inside the sublocality of %@ and pin code is %@",name,subLocality,postalCode]; 


      UIAlertView *Alert=[[UIAlertView alloc]initWithTitle:@"Location Update" message:location delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; 

      [Alert show]; 


     } 

     ]; 

     // } 

     // contains the code you posted to start the timer 
    } 






    - (IBAction)getLocation:(id)sender { 

     [ self startTimer]; 

    } 

ответ

1

Вместо использования метода getLocation, сделать все CLLocationManager инициализации при инициализации класса. В вашей @interface установить свойство удерживать текущее местоположение пользователя:

@property (nonatomic, strong) CLLocation *currentLocation; 

и реализовать метод делегата -locationManager:didUpdateLocations: так:

- (void)locationManager:(CLLocationManager*)manager didUpdateLocations:(NSArray*)locations 
{ 
    // set the current location. The most recent location is always at the end of the 
    // if there are multiple locations 
    _currentLocation = locations[locations.count - 1]; 
} 

Тогда вместо CLLocationCoordinate2D coordinate = [self getLocation];, получить место с:

CLLocationCoordinate2D coordinate = _currentLocation.coordinate; // I think that's the right property. 

Примечание: Убедитесь, что класс соответствует CLLocationManagerDelegate

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