How to retrieve current city name using wifi/3g ip address with iPhone/iOS programming (Objective-c)?
I want to retrieve the current "city name" of the iPhone using ip address of device (wifi/3g). Is there any way to do it? please help me out.
Following is the place where I want the current location.
-(BOOL)fetchAndParseRss{
NSString * CurrentLocation = <I want the retrieved Location here!!>;
NSString * URLrss = [NSString stringWithFormat:@"http://news.google.com/news?q=location:%@&output=rss", CurrentLocation];
NSURL *url = [NSURL URLWithString:URLrss];
NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:url];
}
开发者_Go百科
Actually i am developing an app for myself that displays the news of current city.
You can use CLLocationManager
and MKReverseGeocoder
to get users city.
First add CLLocationManager
and start updating user location
- (void)startLocationManager
{
if (locManager==nil)
locManager = [[CLLocationManager alloc] init];
if (locManager.locationServicesEnabled)
{
NSLog(@"User has opted out of service on it error");
} else {
locManager.delegate = self;
locManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
[locManager startUpdatingLocation];
}
}
Then add location manager delegate methods to use MKReverseGeocoder
.
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
NSLog(@"Manager error: %@", [error description]);
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
self.geocoder = [[MKReverseGeocoder alloc] initWithCoordinate:newLocation.coordinate];
[geocoder release];
geocoder.delegate = self;
[geocoder start];
[manager stopUpdatingLocation];
}
and of course you have to implement MKReverseGeocoder
Delegate methods
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error
{
NSLog(@"reverseGeocoder:%@ didFailWithError:%@", geocoder, error);
}
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark
{
// with the placemark you can now retrieve the city name
NSString *city = [placemark.addressDictionary objectForKey:@"City"];
NSLog(@"City is %@", city);
}
This method can be use if user gives permission to your application for location manager.
One option would be to make an HTTP request to a website like geoiptool.com and scrape the city information from the response. I'm unsure how much success you'll have when using mobile phone networks, though—wifi worked when I tried it on my phone, but 3G didn't.
精彩评论