我想在我的 iPhone 应用程序中获取我当前的城市名称。
我目前正在使用 CLLocationManager 获取纬度和经度,然后将坐标传递给 CLGeocoder。
CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
[geoCoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
for (CLPlacemark * placemark in placemarks) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Current City" message:[NSString stringWithFormat:@"Your Current City:%@",[placemark locality]] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:@"Cancel", nil];
[alert show];
}
}];
这在 iOS 5.0 中运行良好,但在 iOS 4.3 中无法运行。
作为替代方案,我开始使用 Google Web 服务
-(void)findLocationFor:(NSString *)latitudeStr
andLontitude:(NSString *)longtitudeStr{
if ([self connectedToWiFi]){
float latitude = [latitudeStr floatValue];
float longitude = [longtitudeStr floatValue];
NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithObjectsAndKeys:
[NSString stringWithFormat:@"%f,%f", latitude, longitude], @"latlng", nil];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://maps.googleapis.com/maps/api/geocode/json"]];
[parameters setValue:@"true" forKey:@"sensor"];
[parameters setValue:[[NSLocale currentLocale] objectForKey:NSLocaleLanguageCode] forKey:@"language"];
NSMutableArray *paramStringsArray = [NSMutableArray arrayWithCapacity:[[parameters allKeys] count]];
for(NSString *key in [parameters allKeys]) {
NSObject *paramValue = [parameters valueForKey:key];
[paramStringsArray addObject:[NSString stringWithFormat:@"%@=%@", key, paramValue]];
}
NSString *paramsString = [paramStringsArray componentsJoinedByString:@"&"];
NSString *baseAddress = request.URL.absoluteString;
baseAddress = [baseAddress stringByAppendingFormat:@"?%@", paramsString];
[request setURL:[NSURL URLWithString:baseAddress]];
NSError *error = nil;
NSURLResponse *response = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (response == nil) {
if (error != nil) {
}
}
else {
NSDictionary *responseDict = [returnData objectFromJSONData];
NSArray *resultsArray = [responseDict valueForKey:@"results"];
NSMutableArray *placemarksArray = [NSMutableArray arrayWithCapacity:[resultsArray count]];
for(NSDictionary *placemarkDict in resultsArray){
NSDictionary *coordinateDict = [[placemarkDict valueForKey:@"geometry"] valueForKey:@"location"];
float lat = [[coordinateDict valueForKey:@"lat"] floatValue];
float lng = [[coordinateDict valueForKey:@"lng"] floatValue];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:[NSString stringWithFormat:@"%.f",lat] forKey:@"latitude"];
[dict setObject:[NSString stringWithFormat:@"%.f",lng] forKey:@"longitude"];
[dict setObject:[placemarkDict objectForKey:@"formatted_address"] forKey:@"address"];
[placemarksArray addObject:dict];
[dict release];
}
NSDictionary *placemark = [placemarksArray objectAtIndex:0];
}
}
}
但是我得到的响应太长了,这意味着我仍然无法获取城市名称,因为在某些情况下,此 Web 服务会提供有关坐标的所有其他信息,期望城市名称。
任何人都可以帮助我吗?