- 最近項(xiàng)目要用到手機(jī)的ip地址和地理位置枚粘,如果用戶不允許當(dāng)前APP定位那么想要獲得地理位置就麻煩了馅闽,獲取手機(jī)的ip地址在網(wǎng)上查了一些資料,全是獲取局域網(wǎng)的ip地址馍迄,我想說獲取局域網(wǎng)的有個卵用福也,所有文章千篇一律,全是抄的攀圈。并沒有解決我的問題暴凑,其實(shí)獲取用戶的ip在后臺那里是超級容易,只要用戶訪問數(shù)據(jù) 后臺就知道用戶的IP赘来,那么交給前端做现喳,其實(shí)也不難,下面步入正題···下面上代碼:
- (void)viewDidLoad {
[super viewDidLoad];
[self urlRequestOperation];
}
-(void)urlRequestOperation{
NSString *URLTmp = @"http://ip.taobao.com/service/getIpInfo.php?ip=myip";
NSString *URLTmp1 = [URLTmp stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; //轉(zhuǎn)碼成UTF-8 否則可能會出現(xiàn)錯誤
// [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]];
//系統(tǒng)自帶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];
}
由于項(xiàng)目中用到了AFNetworking 所以上述代碼解析數(shù)據(jù)用到了他犬辰,下面請看效果圖
969236-aff65d765db09a88.png