簡體   English   中英

如何使用iPhone / iOS編程(Objective-c)使用wifi / 3g ip地址檢索當前城市名稱?

[英]How to retrieve current city name using wifi/3g ip address with iPhone/iOS programming (Objective-c)?

我想使用設備的ip地址(wifi / 3g)檢索iPhone的當前“城市名稱”。 有什么辦法嗎? 請幫幫我。

以下是我想要當前位置的地方。

-(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];
}

其實我正在為自己開發一個顯示當前城市新聞的應用程序。

您可以使用CLLocationManagerMKReverseGeocoder來獲取用戶城市。

首先添加CLLocationManager並開始更新用戶位置

- (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];
    }
}

然后添加位置管理器委托方法以使用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];
}

當然,您必須實現MKReverseGeocoder Delegate方法

- (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);
}

如果用戶為您的應用程序授予位置管理員權限,則可以使用此方法。

一種選擇是向geoiptool.com等網站發出HTTP請求,並從響應中抓取城市信息。 我不確定你在使用手機網絡時會有多大的成功,雖然我在手機上試用了wifi,但3G並沒有。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM