MKReverseGeocoder устарел

Я только что увидел, что MKReverseGeocoder устарел. Вопрос в том, как проще всего перейти на CLGeocoder? Извините за чрезвычайно длинный исходный код (я думаю, вы думаете, что это довольно просто, но я новичок в этом). Это то, что я получил раньше...

StoreLocation.h

@interface StoreLocation : NSObject <MKAnnotation> {

    CLLocationCoordinate2D coordinate;

}

@property (nonatomic, readwrite) CLLocationCoordinate2D coordinate;
@property (nonatomic, readwrite) NSString *subtitle;

-(id)initWithCoordinate:(CLLocationCoordinate2D) coordinate;

- (NSString *)subtitle;

- (NSString *)title;

@end

Расположение магазина.м

@implementation StoreLocation
@synthesize coordinate,subtitle;

-(NSString *)subtitle{

    NSUserDefaults *userDef = [NSUserDefaults standardUserDefaults];
    if ([userDef boolForKey:@"SavedAddress"]) {
        NSString *savedAddress = [[NSUserDefaults standardUserDefaults] stringForKey:@"SavedAddress"];
        return savedAddress;
    }
    else {
        return subtitle;
    }
}

-(id)initWithCoordinate:(CLLocationCoordinate2D) coor{
    self.coordinate=coor;
    return self;
}


- (void)setCoordinate:(CLLocationCoordinate2D)coor {
    MKReverseGeocoder *geocoder = [[MKReverseGeocoder alloc] initWithCoordinate:coor];
    geocoder.delegate = self;
    coordinate = coor;
    [geocoder start];
}

- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error {
    NSLog(@"fail %@", error);
}

- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark {
    self.subtitle = [placemark.addressDictionary valueForKey:@"Street"];

    NSUserDefaults *userDef = [NSUserDefaults standardUserDefaults];
    [userDef setValue:subtitle forKey:@"SavedAddress"];
}

MapViewController.m

    -(void) locationManager: (CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation*)oldLocation{

    MKGeocoder *geocoder = [[MKReverseGeocoder alloc] initWithCoordinate:location];
        [geocoder start];
    }


    - (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark{
        NSString *streetAddress = [NSString stringWithFormat:@"%@, %@",
                                   [placemark.addressDictionary objectForKey:(NSString *)kABPersonAddressStreetKey],
                                   [placemark.addressDictionary objectForKey:(NSString *)kABPersonAddressCityKey]];

        mapView.userLocation.subtitle = streetAddress;      
    }
-(IBAction)storeLocation {

    StoreLocation *position=[[StoreLocation alloc] initWithCoordinate:location];    [mapView addAnnotation:position]; }


    - (MKAnnotationView *)mapView:(MKMapView *)mapview
                viewForAnnotation:(id <MKAnnotation>)dropPin
    {
        if ([dropPin isKindOfClass:MKUserLocation.class])
        {
            return nil;
        }

        MKPinAnnotationView *pinView = (MKPinAnnotationView*)[mapview dequeueReusableAnnotationViewWithIdentifier:@"annot"];
        if (!pinView)
        {
            pinView = [[MKPinAnnotationView alloc] initWithAnnotation:dropPin reuseIdentifier:@"annot"];
            pinView.canShowCallout = YES;
        }
        else {
            pinView.annotation = dropPin;
        }
        return pinView;
    }

Спасибо тысячу раз!


person Christoffer    schedule 12.11.2012    source источник


Ответы (1)


Может вот так?

MKReverseGeocoder устарел во всех прошивках после iOS4. Это просто означает, что теперь он устарел и не одобряет использование устаревшего класса. Вместо этого используйте CLGeocoder, например:

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

    [geocoder reverseGeocodeLocation:self.locationManager.location // You can pass aLocation here instead 
                   completionHandler:^(NSArray *placemarks, NSError *error) {

                       dispatch_async(dispatch_get_main_queue(),^ {
                           // do stuff with placemarks on the main thread

                       if (placemarks.count == 1) {

                       CLPlacemark *place = [placemarks objectAtIndex:0];


                       NSString *zipString = [place.addressDictionary valueForKey:@"ZIP"];

                       [self performSelectorInBackground:@selector(showWeatherFor:) withObject:zipString];

                       }

 });

}]; Если вы хотите реверсивно геокодировать жестко закодированную пару координат -

Инициализируйте местоположение CLLocation с помощью вашей широты и долготы:

CLLocation *aLocation = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];

Я также хочу отметить, что вы все еще можете использовать MKReverseGeocoder. Однако он может быть удален с будущими обновлениями iOS.

person David Raijmakers    schedule 12.11.2012