在 iOS 中从邮政编码自动填充城市和州 [英] Autofill city and state from zip code in iOS

查看:29
本文介绍了在 iOS 中从邮政编码自动填充城市和州的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

推荐答案

使用Google GeoCoding API提取信息,如果你想发送邮政编码接收其他信息,使用这个:>

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:@"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);

如果您的邮政编码变量是 32000,您将获得 这个 JSON 结果:

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

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

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

这篇关于在 iOS 中从邮政编码自动填充城市和州的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆