2015-02-17 2 views
2

Я хочу определить текущее местоположение пользователя в своем приложении. Я использую объективный c.It работает нормально в симуляторе, но при тестировании на устройстве ниже появляется ошибка.Проблема с местоположением в устройстве iPhone

didFailWithError: Error Domain=kCLErrorDomain Code=0 "The operation couldn’t be completed. (kCLErrorDomain error 0.)" 

Пожалуйста, помогите мне решить эту проблему. Я использую Lat long value для определения метки места в своем приложении.

if(version<8.0) 
{ 
    locationManager = [[CLLocationManager alloc] init]; 


    locationManager.delegate = self; 
    locationManager.desiredAccuracy = kCLLocationAccuracyBest; 

    [locationManager startUpdatingLocation]; 
} 
else 
{ 
    locationManager = [[CLLocationManager alloc] init]; 
    locationManager.delegate = self; 
    // Check for iOS 8. Without this guard the code will crash with "unknown selector" on iOS 7. 
    if ([locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) { 
     [locationManager requestWhenInUseAuthorization]; 
    } 
    [locationManager startUpdatingLocation]; 
} 

Вот метод делегата

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{ 
NSLog(@"didFailWithError: %@", error); 
UIAlertView *errorAlert = [[UIAlertView alloc] 
          initWithTitle:@"Error" message:@"Failed to Get Your Location" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; 
[errorAlert show];} 



- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{ 
NSLog(@"didUpdateToLocation: %@", newLocation); 
CLLocation *currentLocation = newLocation; 


if (currentLocation != nil) { 
    NSString *longitude = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude]; 
    NSString *latitude = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude]; 

    CLGeocoder * geoCoder = [[CLGeocoder alloc] init]; 



    [geoCoder reverseGeocodeLocation: locationManager.location completionHandler: 
    ^(NSArray *placemarks, NSError *error) { 


     CLPlacemark *placemark = [placemarks objectAtIndex:0]; 


     NSString *placemark_str = [placemark locality]; 
     subAdminArea.text=placemark.subAdministrativeArea; 

     NSString *are_str = [placemark subLocality]; 

      subAdminArea.text=placemark.subAdministrativeArea; 


     NSString *location_str=[NSString stringWithFormat:@"%@,%@",are_str,placemark_str]; 

     [[NSUserDefaults standardUserDefaults]setValue:location_str forKey:@"Location"]; 

     NSLog(@"place mark str: %@",placemark_str); 


    }]; 

}} 


- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{ 
NSLog(@"%@", [locations lastObject]); 

CLGeocoder * geoCoder = [[CLGeocoder alloc] init]; 


[geoCoder reverseGeocodeLocation: [locations lastObject] completionHandler: 
^(NSArray *placemarks, NSError *error) { 


    CLPlacemark *placemark = [placemarks objectAtIndex:0]; 


    NSString *placemark_str = [placemark locality]; 
    NSString *are_str = [placemark subLocality]; 



    NSString *location_str=[NSString stringWithFormat:@"%@,%@",are_str,placemark_str]; 

    [[NSUserDefaults standardUserDefaults]setValue:location_str forKey:@"Location"]; 




}];} 




- (void)requestAlwaysAuthorization{ 
CLAuthorizationStatus status = [CLLocationManager authorizationStatus]; 

// If the status is denied or only granted for when in use, display an alert 
if (status == kCLAuthorizationStatusAuthorizedWhenInUse || status == kCLAuthorizationStatusDenied) { 
    NSString *title; 
    title = (status == kCLAuthorizationStatusDenied) ? @"Location services are off" : @"Background location is not enabled"; 
    NSString *message = @"To use background location you must turn on 'Always' in the Location Services Settings"; 

    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title 
                 message:message 
                 delegate:self 
               cancelButtonTitle:@"Cancel" 
               otherButtonTitles:@"Settings", nil]; 
    [alertView show]; 
} 
// The user has not enabled any location services. Request background authorization. 
else if (status == kCLAuthorizationStatusNotDetermined) { 
    [locationManager requestAlwaysAuthorization]; 
}} 

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{ 
if (buttonIndex == 1) { 
    // Send the user to the Settings for this app 
    NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString]; 
    [[UIApplication sharedApplication] openURL:settingsURL]; 
}} 

Я также обновить свой файл Plist с NSLocationAlwaysUsageDescription-> Струнный & NSLocationWhenInUseUsageDescription -> String.

Thank you.

+0

Я считаю, что вы тестируете это на устройстве iOS 8 ... Правильно? Для iOS 8 что-то изменилось ... пожалуйста, google, прежде чем спрашивать здесь ... –

+0

Нет устройства ios 7, и я знаю о проблеме ios 8 с местоположением. Он отлично работает в симуляторе для ios 7 и 8, но не в устройстве. Спасибо, Фахим. – user3418619

+0

добавьте код также к вопросу .. это может помочь читателям выяснить проблему ... :) – raki

ответ

-1

1) убедитесь, что у вас действительно есть действующий WiFi и 3G соединение

если вы делаете то

2) перейдите в настройки и сбросить службы определения местоположения

3), а затем сбросить настройки сети

+0

Я уже применяю все эти шаги, но не работаю в своем состоянии. Спасибо за повторное воспроизведение me.and скажите, есть ли у вас другое решение или рабочий код – user3418619

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