定位所在城市

来源:互联网 发布:一个php页面的完整代码 编辑:程序博客网 时间:2024/06/04 18:28
这个方法里- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
--------------------------------------------
//自动定位获取是哪个城市

    [locationManager stopUpdatingLocation];
    locat=[newLocation coordinate];
     CLGeocoder *geocoder=[[CLGeocoder alloc]init];
     [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
     if (placemarks.count>0) {
     CLPlacemark *placenark=[placemarks objectAtIndex:0];
     NSLog(@"%@============%@",[placenark locality],[placenark subLocality]);
     [self showWithlocation:locat];
     }
     else{
     NSLog(@"-------定位失败-----");
     }
     }];

调用的自定义的一个方法------------------------------------------
-(void)showWithlocation:(CLLocationCoordinate2D)location
 {
 
 
 
 CLGeocoder*Geocoder=[[CLGeocoder alloc]init];
 CLLocation *loc = [[CLLocation alloc] initWithLatitude:location.latitude longitude:location.longitude];
 
 CLGeocodeCompletionHandler handler = ^(NSArray *place, NSError *error) {
 
 for (CLPlacemark *placemark in place) {
 NSString *cityStr=[placemark.addressDictionary objectForKey:@"City"];
 //访问完数据后将地址存入本地
 NSUserDefaults *userDefaults=[NSUserDefaults standardUserDefaults];
 [userDefaults setObject:cityStr forKey:@"cityName"];
 [userDefaults synchronize];
 [cityButton setTitle:cityStr forState:UIControlStateNormal];
 
 NSLog(@"%@",cityStr);
 break;
 
 }
 };
 [Geocoder reverseGeocodeLocation:loc completionHandler:handler];
 
 
 }