如何在Objective-C中找到IP地址的地理位置?

时间:2014-08-05 08:10:16

标签: ios objective-c localization

如何确定IP地址所在的国家/地区?

1 个答案:

答案 0 :(得分:10)

感谢您的评论!

我从主题How to get user external IP and Geolocation Programmatically in iOS中找到答案并将代码编辑为结果:

NSMutableURLRequest *requestHTTP = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://ip-api.com/json"]
                                                           cachePolicy:NSURLRequestReloadIgnoringCacheData  timeoutInterval:10];

[requestHTTP setHTTPMethod:@"GET"];
[requestHTTP setValue: @"text/json" forHTTPHeaderField:@"Accept"];

AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:requestHTTP];
op.responseSerializer = [AFJSONResponseSerializer serializer];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"IP response: %@ ",responseObject);
    NSString *myIP = [responseObject valueForKey:@"query"];
    NSLog(@"IP: %@", myIP);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", [error localizedDescription]);

}];
[op start];

谢谢!