2015-05-25 5 views
0

Я новичок в теме MapView. Сейчас я работаю над видом карты. Я получаю данные о долготе и широте местоположения сан-франциска. Я тестирую в симуляторе. Он не показывает текущие значения долготы и широты местоположения.Не удалось найти местоположение пользователя?

С помощью этого урока http://www.creativeworkline.com/2014/12/core-location-manager-ios-8-fetching-location-background/ Я разрабатываю приложение.

В AppDelegate файла я написал следующий код, как этого

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 

    UIAlertView * alert; 

    //We have to make sure that the Background App Refresh is enable for the Location updates to work in the background. 
    if([[UIApplication sharedApplication] backgroundRefreshStatus] == UIBackgroundRefreshStatusDenied){ 

     alert = [[UIAlertView alloc]initWithTitle:@"" 
              message:@"The app doesn't work without the Background App Refresh enabled. To turn it on, go to Settings > General > Background App Refresh" 
             delegate:nil 
           cancelButtonTitle:@"Ok" 
           otherButtonTitles:nil, nil]; 
     [alert show]; 

    }else if([[UIApplication sharedApplication] backgroundRefreshStatus] == UIBackgroundRefreshStatusRestricted){ 

     alert = [[UIAlertView alloc]initWithTitle:@"" 
              message:@"The functions of this app are limited because the Background App Refresh is disable." 
             delegate:nil 
           cancelButtonTitle:@"Ok" 
           otherButtonTitles:nil, nil]; 
     [alert show]; 

    } else{ 

     self.locationTracker = [[LocationTracker alloc]init]; 
     [self.locationTracker startLocationTracking]; 

     //Send the best location to server every 60 seconds 
     //You may adjust the time interval depends on the need of your app. 
     NSTimeInterval time = 60.0; 
     self.locationUpdateTimer = 
     [NSTimer scheduledTimerWithTimeInterval:time 
             target:self 
             selector:@selector(updateLocation) 
             userInfo:nil 
             repeats:YES]; 
    } 

    return YES; 
} 

Я импортируемый Местоположение класса Tracker в моем ViewController

и я написал следующий код, чтобы получить название местоположения и addresss

CLGeocoder *geoCoder = [[CLGeocoder alloc]init]; 
    __block NSString *returnAddress = nil; 

    [geoCoder reverseGeocodeLocation:self.appDelgate.locationTracker.myLastLocation_ completionHandler:^(NSArray *placemarks, NSError *error) { 

     CLPlacemark *placemark = [placemarks lastObject]; 

     if (placemark) 
     { 
      returnAddress = [NSString stringWithFormat:@"%@ %@",placemark.subLocality,placemark.subAdministrativeArea]; 
      [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithString:returnAddress] forKey:@"address"]; 

     } 


    }]; 

Теперь моя проблема в том, что она не идет внутри блока. Так что я получаю «returnAddress» как (null).

я написал, как это, даже если он не придет

- (void)updateLocationToServer { 

    NSLog(@"updateLocationToServer"); 

    // Find the best location from the array based on accuracy 
    NSMutableDictionary * myBestLocation = [[NSMutableDictionary alloc]init]; 

    for(int i=0;i<self.shareModel.myLocationArray.count;i++){ 
     NSMutableDictionary * currentLocation = [self.shareModel.myLocationArray objectAtIndex:i]; 

     if(i==0) 
      myBestLocation = currentLocation; 
     else{ 
      if([[currentLocation objectForKey:ACCURACY]floatValue]<=[[myBestLocation objectForKey:ACCURACY]floatValue]){ 
       myBestLocation = currentLocation; 
      } 
     } 
    } 
    NSLog(@"My Best location:%@",myBestLocation); 

    NSLog(@"latitude %@",[myBestLocation valueForKey:@"latitude"]); 

     NSLog(@"longitude %@",[myBestLocation valueForKey:@"longitude"]); 

    self.DICT=[NSDictionary dictionaryWithDictionary:myBestLocation]; 

    //If the array is 0, get the last location 
    //Sometimes due to network issue or unknown reason, you could not get the location during that period, the best you can do is sending the last known location to the server 
    if(self.shareModel.myLocationArray.count==0) 
    { 
     NSLog(@"Unable to get location, use the last known location"); 

     self.myLocation=self.myLastLocation; 
     self.myLocationAccuracy=self.myLastLocationAccuracy; 

    }else{ 
     CLLocationCoordinate2D theBestLocation; 
     theBestLocation.latitude =[[myBestLocation objectForKey:LATITUDE]floatValue]; 
     theBestLocation.longitude =[[myBestLocation objectForKey:LONGITUDE]floatValue]; 
     self.myLocation=theBestLocation; 
     self.myLocationAccuracy =[[myBestLocation objectForKey:ACCURACY]floatValue]; 
    } 

    NSLog(@"Send to Server: Latitude(%f) Longitude(%f) Accuracy(%f)",self.myLocation.latitude, self.myLocation.longitude,self.myLocationAccuracy); 

     //TODO: Your code to send the self.myLocation and self.myLocationAccuracy to your server 

    //After sending the location to the server successful, remember to clear the current array with the following code. It is to make sure that you clear up old location in the array and add the new locations from locationManager 
    [self.shareModel.myLocationArray removeAllObjects]; 
    self.shareModel.myLocationArray = nil; 
    self.shareModel.myLocationArray = [[NSMutableArray alloc]init]; 

    CLGeocoder *geoCoder = [[CLGeocoder alloc]init]; 
    __block NSString *returnAddress = nil; 
    self.locationActual = [[CLLocation alloc]initWithLatitude:[[myBestLocation objectForKey:LATITUDE]floatValue] longitude:[[myBestLocation objectForKey:LONGITUDE]floatValue]]; 

    //CLGeocoder *geoCoder = [[CLGeocoder alloc]init]; 
    // __block NSString *returnAddress = nil; 

    CLLocation *locloc = [[CLLocation alloc] initWithLatitude:[[myBestLocation objectForKey:LATITUDE]floatValue] longitude:[[myBestLocation objectForKey:LONGITUDE]floatValue]]; 

    [geoCoder reverseGeocodeLocation:locloc completionHandler:^(NSArray *placemarks, NSError *error) { 

     CLPlacemark *placemark = [placemarks lastObject]; 

     if (placemark) 
     { 
      returnAddress = [NSString stringWithFormat:@"%@ %@",placemark.subLocality,placemark.subAdministrativeArea]; 
      //[[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithString:returnAddress] forKey:@"address"]; 
      UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:returnAddress delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil]; 
      [alertView show]; 
     } 


    }]; 


    } 

Какую ошибку я сделал здесь. Может кто-нибудь может помочь устранить эту путаницу. Спасибо заранее.

+0

вы можете проверить, что вы получаете в myLastlocation_? – abhishekkharwar

+0

Я добавил свойство @property (неатомное) CLLocation * myLastLocation_; в Location Tracker.h –

+0

Как я могу получить информацию о местоположении в моем ViewController –

ответ

1

Вы уверены, что используете обратный адрес после завершения блока? Я использовал приведенный выше код и его работоспособность.

Здесь вы можете скачать sample code

CLGeocoder *geoCoder = [[CLGeocoder alloc]init]; 
    __block NSString *returnAddress = nil; 

    CLLocation *locloc = [[CLLocation alloc] initWithLatitude:12.92243 longitude:80.23893]; 

    [geoCoder reverseGeocodeLocation:locloc completionHandler:^(NSArray *placemarks, NSError *error) { 

     CLPlacemark *placemark = [placemarks lastObject]; 

     if (placemark) 
     { 
      returnAddress = [NSString stringWithFormat:@"%@ %@",placemark.subLocality,placemark.subAdministrativeArea]; 
      //[[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithString:returnAddress] forKey:@"address"]; 
      UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:returnAddress delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil]; 
      [alertView show]; 
     } 


    }]; 


//If you try to access retunAddress here you will get nil. 

ВЫВОД

enter image description here

+0

Можете ли вы поделиться лат и длинные ценности с нами? – abhishekkharwar

+0

Я отредактировал мой вопрос сейчас. Можете ли вы проверить его и сообщить мне, какую ошибку я сделал там. –

+0

Я пытаюсь получить этот обратный адрес в моем MainViewController. Можно ли его получить? –

0

Перейти к iOS Simulator -> Debug -> Location -> Custom location ... И введите ваши длинные/lat координаты.

0

В тренажере нет никакого способа, чтобы получить фактические GPS на основе данных, поэтому вы должны имитировать это с вашей лат длиной, которые вы можете установить, перейдя

Debug -> Location -> Custom Location 

и установить свои значения там. enter image description here

0

Возможно, вы моделируете местоположение в симуляторе. На панели консоли xCode имеется кнопка со стрелкой. Нажмите эту кнопку и выберите «Не имитировать местоположение». Для справки см. Изображение. enter image description here

Если это не решит проблему, запустите приложение. Перейдите в меню Debug симулятора и выберите опцию «Custom location», как показано на изображении. enter image description here

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