iOS 获取手机的iP地址,各种地址,不是局域网ip
2015-12-03 本文已影响3759人
我的天空蔚蓝色
- 最近项目要用到手机的ip地址和地理位置,如果用户不允许当前APP定位那么想要获得地理位置就麻烦了,获取手机的ip地址在网上查了一些资料,全是获取局域网的ip地址,我想说获取局域网的有个卵用,所有文章千篇一律,全是抄的。并没有解决我的问题,其实获取用户的ip在后台那里是超级容易,只要用户访问数据 后台就知道用户的IP,那么交给前端做,其实也不难,下面步入正题···下面上代码:
- (void)viewDidLoad {
[super viewDidLoad];
[self urlRequestOperation];
}
-(void)urlRequestOperation{
NSString *URLTmp = @"http://ip.taobao.com/service/getIpInfo.php?ip=myip";
NSString *URLTmp1 = [URLTmp stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; //转码成UTF-8 否则可能会出现错误
// [URLTmp stringByAddingPercentEncodingWithAllowedCharacters:(nonnull NSCharacterSet *)]
URLTmp = URLTmp1;
NSURLRequest *request =
[NSURLRequest requestWithURL:[NSURL URLWithString: URLTmp]];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:
^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Success: %@", operation.responseString);
NSString *requestTmp = [NSString stringWithString:operation.responseString];
NSData *resData = [[NSData alloc] initWithData:[requestTmp dataUsingEncoding:NSUTF8StringEncoding]];
//系统自带JSON解析
NSDictionary *resultDic =
[NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableLeaves error:nil];
NSLog(@"aaaaaaa=====%@",resultDic);
UILabel * label1 =
[[UILabel alloc]initWithFrame:CGRectMake(100, 20, 200, 30)];
label1.backgroundColor = [UIColor yellowColor];
label1.text = [[resultDic objectForKey:@"data"] objectForKey:@"ip"];
[self.view addSubview:label1];
UILabel * label2 = [[UILabel alloc]initWithFrame:CGRectMake(100, 70, 200, 30)];
label2.backgroundColor = [UIColor yellowColor];
label2.text = [[resultDic objectForKey:@"data"] objectForKey:@"city"];
[self.view addSubview:label2];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Failure: %@", error);
}];
[operation start];
}
由于项目中用到了AFNetworking 所以上述代码解析数据用到了他,下面请看效果图