Deepak Thakur Deepak Thakur - 3 months ago 49
iOS Question

Autofill city and state from zip code in iOS

I have three textfields in my view.
1. Zip code, 2. City and 3. State.

How to autofill city and state field from the zip code in 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?


Use the Google GeoCoding API to extract Information, if you want to send zip code to receive other information, use this:

NSString *strRequestParams = [NSString stringWithFormat:@"",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);

If your zipcode variable is 32000, you will get the this JSON result:

You can parse this json to extract any information you want including Country, City, longitude, latitude etc