在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? } 

使用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); 

如果你的zipcodevariables是32000,你将得到这个 JSON结果:

你可以parsing这个json来提取你想要的任何信息,包括国家,城市,经度,纬度等

我试图避免Google的服务,因为他们倾向于在一定的使用水平上收费。 以下是使用Apple框架的解决scheme:

  #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 } }]; } 

由ar-studios公司的答案是现货,因为它不会引起对Google服务的依赖。

不过,如果有意义的话,我也会根据用户的input或仅限美国来限制国家/地区代码。 不限制它给出不可预知的结果,因为地理编码器可以返回来自不同国家的多个匹配。

  #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 } }]; } 

这里是所有以上更正的Swift 3版本。

 func zipToAddress(zip: String, onSuccess: @escaping (String, String, String) -> Void, onFail: @escaping () -> Void) { let geoCoder = CLGeocoder(); let params = [ String(CNPostalAddressPostalCodeKey): zip, String(CNPostalAddressISOCountryCodeKey): "US", ] geoCoder.geocodeAddressDictionary(params) { (plasemarks, error) -> Void in if let plases = plasemarks { if plases.count > 0 { let firstPlace = plases[0] print( "City \(firstPlace.locality) state \(firstPlace.administrativeArea) and country \(firstPlace.country) and iso country \(firstPlace.country)") let city = firstPlace.locality let state = firstPlace.administrativeArea let country = firstPlace.country onSuccess(city != nil ? city! : "", state != nil ? state! : "", country ?? "Not found") return; } } onFail() } } 

尽pipealex_c和ar-studios的答案很好,但是如果您不喜欢AddressBookUI或字典,那么您可以简单地使用geocoder上的geocodeAddressString:completionHandler:方法传递邮政编码,这对于查找:

 [[CLGeocoder new] geocodeAddressString:zip completionHandler:^(NSArray *placemarks, NSError *error) { if (placemarks.count) { CLPlacemark *placemark = placemarks.firstObject; NSString *city = placemark.locality; NSString *state = placemark.administrativeArea; } }]; 
 static func zipToAddress(zip: String, onSuccess: (String, String) -> Void, onFail: () -> Void) { var geoCoder = CLGeocoder(); var params = [ String(kABPersonAddressZIPKey): zip, String(kABPersonAddressCountryCodeKey): "US", ] geoCoder.geocodeAddressDictionary(params) { (plasemarks, error) -> Void in var plases = plasemarks as? Array<CLPlacemark> if plases != nil && plases?.count > 0 { var firstPlace = plases?[0] var city = firstPlace?.addressDictionary[String(kABPersonAddressCityKey)] as? String var state = firstPlace?.addressDictionary[String(kABPersonAddressStateKey)] as? String var country = firstPlace?.addressDictionary[String(kABPersonAddressCountryKey)] as? String // US onSuccess(city != nil ? city! : "", state != nil ? state! : "") return; } onFail() } } 

与swift一样,我不能把这个添加为评论(点不enoght)