通过iOS中的邮政编码自动填充城市和州

Dee*_*kur 12 objective-c google-api ios

我认为我有三个文本域.1.邮政编码,2.城市和3.州.

如何从iOS中的邮政编码自动填充城市和州的字段?

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *currentString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    int length = [currentString length];
    if(length > 5)
    {
        return NO;
    }
    if(length == 5)
    {
        [self getCityAndState];
    }
    return YES;
}

- (void) getCityAndState
{
    //How to use google (or any) api to autofill city and state in objective - c?
}
Run Code Online (Sandbox Code Playgroud)

a-r*_*ios 18

我尽量避免使用Google的服务,因为他们倾向于按一定的使用级别收费.以下是使用Apple框架的解决方案:

 #import <CoreLocation/CoreLocation.h>
 #import <AddressBookUI/AddressBookUI.h>

- (void)didEnterZip:(NSString*)zip
{
    CLGeocoder* geoCoder = [[CLGeocoder alloc] init];
    [geoCoder geocodeAddressDictionary:@{(NSString*)kABPersonAddressZIPKey : zip} 
      completionHandler:^(NSArray *placemarks, NSError *error) {
        if ([placemarks count] > 0) {
            CLPlacemark* placemark = [placemarks objectAtIndex:0];

            NSString* city = placemark.addressDictionary[(NSString*)kABPersonAddressCityKey];
            NSString* state = placemark.addressDictionary[(NSString*)kABPersonAddressStateKey];
            NSString* country = placemark.addressDictionary[(NSString*)kABPersonAddressCountryCodeKey];

        } else {
            // Lookup Failed
        }
    }];
}
Run Code Online (Sandbox Code Playgroud)


Kha*_*Ali 10

使用Google GeoCoding API提取信息,如果要发送邮政编码以接收其他信息,请使用:

NSString *strRequestParams = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/geocode/json?address=&components=postal_code:%@&sensor=false",zipCode];

strRequestParams = [strRequestParams stringByAddingPercentEscapesUsingEncoding:NSStringEncodingConversionExternalRepresentation];

NSURL *url = [NSURL URLWithString:strRequestParams];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

[request setHTTPMethod:@"GET"];

NSError *error;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (!response) {
    // "Connection Error", "Failed to Connect to the Internet"
}

NSString *respString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] ;
//NSLog(@"RECEIVED DATA : %@", respString);
Run Code Online (Sandbox Code Playgroud)

如果您的zipcode变量是32000,您将获得 JSON结果:

您可以解析此json以提取您想要的任何信息,包括国家,城市,经度,纬度等

  • @Khanwar Ali:唯一的理由是yi还没有接受你的答案是shouldChangeCharactersInRange:(NSRange)范围方法从zip字段中挑选4个字符而不是文本字段中的5个字符.怎么样? (2认同)

ale*_*x_c 6

ar-studios的答案很明显,因为它没有引入对Google服务的依赖.

但是,如果有意义的话,我还会根据用户的输入或仅限美国来限制国家/地区代码.不限制它会产生不可预测的结果,因为地理编码器可以返回来自不同国家/地区的多个匹配.

 #import <CoreLocation/CoreLocation.h>
 #import <AddressBookUI/AddressBookUI.h>

- (void)didEnterZip:(NSString*)zip
{
    CLGeocoder* geoCoder = [[CLGeocoder alloc] init];
    [geoCoder geocodeAddressDictionary:@{(NSString*)kABPersonAddressZIPKey : zip, 
          (NSString*)kABPersonAddressCountryCodeKey : @"US"} 
      completionHandler:^(NSArray *placemarks, NSError *error) {
        if ([placemarks count] > 0) {
            CLPlacemark* placemark = [placemarks objectAtIndex:0];

            NSString* city = placemark.addressDictionary[(NSString*)kABPersonAddressCityKey];
            NSString* state = placemark.addressDictionary[(NSString*)kABPersonAddressStateKey];
            NSString* country = placemark.addressDictionary[(NSString*)kABPersonAddressCountryCodeKey];

        } else {
            // Lookup Failed
        }
    }];
}
Run Code Online (Sandbox Code Playgroud)


Nat*_*ton 5

虽然 alex_c 和 ar-studios 的答案效果很好,但如果您不想对AddressBookUI字典或字典大惊小怪,您可以简单地使用该geocodeAddressString:completionHandler:方法geocoder单独传递邮政编码,这足以进行查找:

[[CLGeocoder new] geocodeAddressString:zip completionHandler:^(NSArray *placemarks, NSError *error) {
    if (placemarks.count) {
        CLPlacemark *placemark = placemarks.firstObject;

        NSString *city = placemark.locality;
        NSString *state = placemark.administrativeArea;
    }
}];
Run Code Online (Sandbox Code Playgroud)

在斯威夫特:

CLGeocoder().geocodeAddressString(zip) { (placemarks, error) in
    if let result = placemarks?.first {
        let city = result.locality
        let state = result.administrativeArea
    }
}
Run Code Online (Sandbox Code Playgroud)