在公司做项目的时候用到根据手机的IP来判断用户所在地以及运营商来给用户分配线路,首先要怎样获取外网IP,其实很简单用第三方的网站就可以了
NSError *error;
NSURL *ipURL = [NSURL URLWithString:@"http://ifconfig.me/ip"];
NSString *ipString = [NSString stringWithContentsOfURL:ipURL encoding:NSUTF8StringEncoding error:&error];
得到了IP,我们就可以根据IP来获取IP的所属国家、省份、运营商等信息。你可以用百度、淘宝、ipip等第三方来查询IP信息,淘宝的查询代码如下:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSURL *url = [NSURL URLWithString:@"http://ifconfig.me/ip"];
NSError *error = nil;
NSString *ipString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
if (error) {
NSLog(@"fetch WAN IP Address failed:%@",error);
dispatch_async(dispatch_get_main_queue(), ^{
});
}else{
dispatch_async(dispatch_get_main_queue(), ^{
NSString *httpUrl = @"http://ip.taobao.com/service/getIpInfo.php";
NSString * httpArg = [NSString stringWithFormat:@"ip=%@",ipString];
NSString *urlStr = [[NSString alloc]initWithFormat: @"%@?%@", httpUrl, httpArg];
// void (^holdBlock)(id response, NSError *error) = [handler copy];
NSURL *url = [NSURL URLWithString: urlStr];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: 10];
[request setHTTPMethod: @"GET"];
[request addValue: @"您自己的apikey" forHTTPHeaderField: @"apikey"];
[NSURLConnection sendAsynchronousRequest: request
queue: [NSOperationQueue mainQueue]
completionHandler: ^(NSURLResponse *response, NSData *data, NSError *error){
if (error) {
NSLog(@"Httperror: %@%ld", error.localizedDescription, (long)error.code);
// holdBlock(nil, error);
} else {
NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"HttpResponseCode:%ld", (long)responseCode);
NSLog(@"HttpResponseBody %@",responseString);
// holdBlock(responseString, nil);
}
}];
});
}
});
用IPIP查询最快,但是免费的限制比较多,付费的查询其实也不算太贵。IPIP的网址:http://www.ipip.net
免费的查询接口:
http://freeapi.ipip.net/IP
付费的查询接口:
http://ipapi.ipip.net/find
请求方式 HTTP GET
参数 addr 118.28.8.8
Header Token cc87f3c77747bccbaaee35006da1ebb65e0bad57
比免费的繁琐一些,但是用afn也比较简单,代码:
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.requestSerializer=[AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:@"token" forHTTPHeaderField:@"Token"];
NSLog(@"%@",manager.requestSerializer.HTTPRequestHeaders);
NSDictionary * dic = @{@"addr":ipString};
[manager GET:@"http://ipapi.ipip.net/find" parameters:dic progress:^(NSProgress * _Nonnull downloadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"------------%@",responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
}];