iOS开发开发-收藏iOS技术交流

iOS 获取手机的iP地址,各种地址,不是局域网ip

2015-12-03  本文已影响3759人  我的天空蔚蓝色
- (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 所以上述代码解析数据用到了他,下面请看效果图

969236-aff65d765db09a88.png
上一篇下一篇

猜你喜欢

热点阅读