在公司做項目的時候用到根據手機的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) {
}];