好的,您如何使用 IP 来做到这一点。
所以,geoplugin.net 有它很棒的 JSON api,它默认 IP 为当前连接,所以你要做的就是向这个地址发出请求:
http://www.geoplugin.net/json.gp
惊人!对我来说,它返回以下数据:
geoPlugin({
"geoplugin_request":"201.6.226.233",
"geoplugin_status":200,
"geoplugin_city":null,
"geoplugin_region":"São Paulo",
"geoplugin_areaCode":0,
"geoplugin_dmaCode":0,
"geoplugin_countryCode":"BR",
"geoplugin_countryName":"Brazil",
"geoplugin_continentCode":"SA",
"geoplugin_latitude":-23.473301,
"geoplugin_longitude":-46.665798,
"geoplugin_regionCode":27,
"geoplugin_regionName":"São Paulo",
"geoplugin_currencyCode":"BRL",
"geoplugin_currencySymbol":"R$",
"geoplugin_currencyConverter":2.0198
})
好吧,现在你要做的就是解析这个“JSON”。它实际上不是 JSON,因为它有这个geoplugin( {data} )
包装器。所以你可以懒惰地执行一些过滤,删除 NSSTring 的那些部分,也许。
我看你很着急,所以我利用空闲时间为你写了一些代码。这是非常不标准的,因为我不知道您是否正在使用任何有用的 REST 框架,但这里是:
NSString *url = [NSString stringWithFormat:@"http://www.geoplugin.net/json.gp"];
NSString *locationData = [[NSString alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:url]]
encoding:NSUTF8StringEncoding]];
locationData = [locationData stringByReplacingOccurrencesOfString:@"geoPlugin(" withString:@""];
locationData = [locationData stringByReplacingOccurrencesOfString:@")" withString:@""];
//user some json parser here.
if([[[locationData JSONValue] valueForkey:@"geoplugin_countryCode"] isEqualToString:@"US"]){
//proceed.
}