- (void)getIp
{
NSLog(@"开始获取ip");
NSError*error;
NSString*ip =@"";
// 方法1 不稳定,有时太慢,有时得不到结果
NSURL *url = [NSURL URLWithString:@"https://ifconfig.me/ip"];
ip = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
// 方法2
NSURL *url = [NSURL URLWithString:@"http://ip.taobao.com/service/getIpInfo.php?ip=myip"];
NSString *response = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
NSDictionary*dicResponse = [responsemj_JSONObject];
if(dicResponse && dicResponse[@"data"]) {
NSDictionary*dicData = dicResponse[@"data"];
if(dicData && dicData[@"ip"]) {
ip = dicData[@"ip"];
}
}
// 方法3
NSURL *url = [NSURL URLWithString:@"http://pv.sohu.com/cityjson?ie=utf-8"];
NSString*response = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
//判断返回字符串是否为所需数据
NSString *prefix = @"var returnCitySN = ";
if([responsehasPrefix:prefix]) {
// 删除多余内容
response = [responsesubstringFromIndex:prefix.length];
response = [responsesubstringToIndex:response.length-1];
NSDictionary*dicResponse = [responsemj_JSONObject];
if(dicResponse && dicResponse[@"cip"]) {
ip = dicResponse[@"cip"];
}
}
NSLog(@"当前网络ip %@", ip);
}