2013-03-07 3 views
6

sto cercando di ottenere l'attuale città e il paese usando CLLocationManager con sottostante Codice -CLLocationManager non ricevendo nome della città

#pragma mark - Core Location Delegate Methods 
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation 
{ 
    CLGeocoder *reverseGeocoder = [[CLGeocoder alloc] init]; 

    [reverseGeocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) 
    { 
     NSLog(@"reverseGeocodeLocation:completionHandler: Completion Handler called!"); 
     if (error){ 
      NSLog(@"Geocode failed with error: %@", error); 
      return; 
     } 

     NSLog(@"Received placemarks: %@", placemarks); 


     CLPlacemark *myPlacemark = [placemarks objectAtIndex:0]; 
     NSString *countryCode = myPlacemark.ISOcountryCode; 
     NSString *countryName = myPlacemark.country; 
     NSString *city1 = myPlacemark.subLocality; 
     NSString *city2 = myPlacemark.locality; 
     NSLog(@"My country code: %@, countryName: %@, city1: %@, city2: %@", countryCode, countryName, city1, city2); 
    }]; 
} 

- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading 
{ 
    CLLocationDirection th=[newHeading trueHeading]; 
    NSLog(@"True Heading value is=%f",th); 
    CLLocationDirection magnetic=[newHeading magneticHeading]; 
    NSLog(@"Magnetic Heading value is=%f",magnetic); 
} 

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error 
{ 
    NSString *errorType = (error.code == kCLErrorDenied) ? NSLocalizedString(@"access_denied", @"") : NSLocalizedString(@"unknown_error", @""); 
    UIAlertView *alert = [[UIAlertView alloc] 
         initWithTitle:NSLocalizedString(@"error_getting_location", @"") 
         message:errorType 
         delegate:nil 
         cancelButtonTitle:NSLocalizedString(@"ok", @"") 
         otherButtonTitles:nil]; 
    [alert show]; 
} 

Dà sempre il risultato con -

Il mio codice Paese: IN, countryName: India, city1: (null), city2: (null)

Non so quale potrebbe essere il problema. Qualcuno ha affrontato questo problema, che non può in grado di ottenere il nome della città usando CLLocationManager

risposta

7

CURA:

- (void) getReverseGeocode 
{ 
    CLGeocoder *geocoder = [[CLGeocoder alloc] init]; 

    if(currentLatLong.count > 0) 
    { 
     CLLocationCoordinate2D myCoOrdinate; 

     myCoOrdinate.latitude = LatValue; 
     myCoOrdinate.longitude = LangValue; 

     CLLocation *location = [[CLLocation alloc] initWithLatitude:myCoOrdinate.latitude longitude:myCoOrdinate.longitude]; 
     [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) 
     { 
      if (error) 
      { 
       NSLog(@"failed with error: %@", error); 
       return; 
      } 
      if(placemarks.count > 0) 
      { 
       NSString *MyAddress = @""; 
       NSString *city = @""; 

       if([placemark.addressDictionary objectForKey:@"FormattedAddressLines"] != NULL) 
        MyAddress = [[placemark.addressDictionary objectForKey:@"FormattedAddressLines"] componentsJoinedByString:@", "]; 
       else 
        MyAddress = @"Address Not founded"; 

       if([placemark.addressDictionary objectForKey:@"SubAdministrativeArea"] != NULL) 
        city = [placemark.addressDictionary objectForKey:@"SubAdministrativeArea"]; 
       else if([placemark.addressDictionary objectForKey:@"City"] != NULL) 
        city = [placemark.addressDictionary objectForKey:@"City"]; 
       else if([placemark.addressDictionary objectForKey:@"Country"] != NULL) 
        city = [placemark.addressDictionary objectForKey:@"Country"]; 
       else 
        city = @"City Not founded"; 

       NSLog(@"%@",city); 
       NSLog(@"%@", MyAddress); 
      } 
     }]; 
    } 
} 
+0

No. Ancora valore nullo restituisce solo – Praveenkumar

+0

@Praveen oh..okay il suo problema del tuo lat e longi (coordinate) .. valore, intendevo cambiare coordinate come londra ... scontroso il mio codice è lavoro :) – iPatel

+0

becoze ... i map alcune coordinate non descrivono l'indirizzo completo come il nome della città, il nome della via ... ecc. :) – iPatel

0

Sai sulle mappe di mele e ci database per la posizione, meglio provare con google places api per ottenere informazioni più accurate e dettagliate per il geocoding inverso. Ho provato lo stesso per auto riempimento dei nomi di luogo, ma non ha funzionato, quindi siamo andati con google luoghi api, non v'è ancora un'API libera provare geonames.org

0

nel file h

#import <CoreLocation/CoreLocation.h> 

@interface ClassDemo : NSObject<NSXMLParserDelegate,CLLocationManagerDelegate> 
{ 
BOOL got; 
BOOL needParser; 
NSMutableArray *currentplaceArray; 
} 
@property (nonatomic, retain) CLLocation *currentLocation; 
@property (nonatomic, getter = isResultsLoaded) BOOL resultsLoaded; 
@property (strong, nonatomic) CLLocationManager *locationManager; 
@property (strong, nonatomic) CLGeocoder *geoCoder; 

a .m

@synthesize locationManager,currentLocation; 
- (void)viewDidLoad 
{ 
got=NO; 
needParser=YES; 

currentplaceArray=[[NSMutableArray alloc]init]; 
//******** Location MAnager Allocation And Intialization********// 
locationManager = [[CLLocationManager alloc] init]; 
locationManager.delegate=self; 
[locationManager startUpdatingLocation]; 
} 
- (void)locationManager:(CLLocationManager *)manager 
didUpdateToLocation:(CLLocation *)newLocation 
     fromLocation:(CLLocation *)oldLocation 
{ 

if ([self isResultsLoaded]) 
{ 
    return; 
} 

[self setResultsLoaded:YES]; 

currentLocation = newLocation; 
NSLog(@"%@",currentLocation); 

NSXMLParser *parser = [[NSXMLParser alloc]initWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat: @"http://maps.googleapis.com/maps/api/geocode/xml?latlng=%f,%f&sensor=false",newLocation.coordinate.latitude,newLocation.coordinate.longitude]]]; 

[parser setDelegate:self]; 
[parser parse]; 

} 
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict 
{ 
NSLog(@"%@",elementName); 
if([elementName isEqualToString:@"formatted_address"]) 
{ 
    got = YES; //got is a BOOL 
} 
} 

-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string 
{ 
if(got&&needParser){ 
    got=NO; 
    NSLog(@"the address is = %@",string); 
    NSArray *tempPlaceArray=[string componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@",/"]]; 
    NSLog(@"%@",tempPlaceArray); 
    for(int i=0; i <[tempPlaceArray count]; i++) 
    { 


     NSString *tempString=[[tempPlaceArray objectAtIndex:i]stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; 
     NSLog(@"%@",tempString); 
     if (![currentplaceArray containsObject:tempString]) 
     { 
      if ([tempString length]!=0) 
      { 
       [currentplaceArray addObject:tempString]; 

      } 
     } 
    } 
    needParser=NO; 
    TempLocation *obj=[[TempLocation alloc]init]; 
    obj.countryName=[currentplaceArray objectAtIndex:[currentplaceArray count]-1]; 
    obj.stateName=[currentplaceArray objectAtIndex:[currentplaceArray count]-2]; 
    obj.cityName=[currentplaceArray objectAtIndex:[currentplaceArray count]-3]; 
    obj.fullAdd=string; 
    [[Database getDBObject]insertIntoCurrentLocationTable:obj.cityName :obj.stateName :obj.countryName:obj.fullAdd]; 


} 

} 

creare una classe di posizione temporanea per l'archiviazione temporanea. E puoi anche salvare nel database come. Goditi la codifica.

0

Anche io ho notato lo stesso problema. Dopo molte tracce ed errori ho trovato il problema con la connessione wifi che stavo usando. Se la potenza del segnale è bassa, otterrai la città come zero. Prova a cambiare la connessione.

+0

Se la potenza del segnale è alta, anche io sto diventando nullo – iEinstein