在IOS中使用CLLocation获取用户当前位置

时间:2015-12-03 08:08:05

标签: ios objective-c iphone geolocation cllocationmanager

我想让用户获得当前位置&我使用CLLocationManager完成的地址并添加了核心位置框架。但反应并不是什么。请分享您的意见。

locationManager = [[CLLocationManager alloc] init]; 
locationManager.desiredAccuracy = kCLLocationAccuracyBest; 
locationManager.delegate = self; [locationManager startUpdatingLocation]; 

和代表

(void)locationManager:(CLLocationManager *)manager didFailWithError: (NSError *)error { 
    NSLog(@"didFailWithError: %@", error); 
    UIAlertView *errorAlert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Failed to Get Your Location" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; 
    [errorAlert show]; 
}

(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations { 
    CLLocation *currentLocation = locations.first; 
    [locationManager setDelegate:nil]; 
    if (currentLocation != nil) { 
        NSString *longitudeLabel = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude]; 
        NSString *latitudeLabel = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude];
    }

5 个答案:

答案 0 :(得分:3)

您需要添加
"NSLocationAlwaysUsageDescription"
"NSLocationWhenInUseUsageDescription"键  Info.plist,并显示一条消息。

答案 1 :(得分:3)

检查我的代码,您可以从当前位置获取地址

- (void)viewDidLoad {
CLGeocoder *ceo;

self.locationManager = [[CLLocationManager alloc]init];
self.locationManager.delegate = self;
[locationManager startUpdatingLocation];
}



-(void)viewDidAppear:(BOOL)animated{
ceo= [[CLGeocoder alloc]init];
[self.locationManager requestWhenInUseAuthorization];
if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
    [self.locationManager requestWhenInUseAuthorization];
}
    CLLocationCoordinate2D coordinate;

coordinate.latitude=locationManager.location.coordinate.latitude;
coordinate.longitude=locationManager.location.coordinate.longitude;
//CLLocationCoordinate2D  ctrpoint;
//  ctrpoint.latitude = ;
//ctrpoint.longitude =f1;
//coordinate.latitude=23.6999;
//coordinate.longitude=75.000;
MKPointAnnotation *marker = [MKPointAnnotation new];
marker.coordinate = coordinate;
NSLog(@"%f",coordinate.latitude);
//[self.mapView addAnnotation:marker];


CLLocation *loc = [[CLLocation alloc]initWithLatitude:coordinate.latitude longitude:coordinate.longitude
                   ];
[ceo reverseGeocodeLocation:loc
          completionHandler:^(NSArray *placemarks, NSError *error) {
              CLPlacemark *placemark = [placemarks objectAtIndex:0];
              NSLog(@"placemark %@",placemark);
              //String to hold address
              NSString *locatedAt = [[placemark.addressDictionary valueForKey:@"FormattedAddressLines"] componentsJoinedByString:@", "];
              NSLog(@"addressDictionary %@", placemark.addressDictionary);

              NSLog(@"placemark %@",placemark.region);
              NSLog(@"placemark %@",placemark.country);  // Give Country Name
              NSLog(@"placemark %@",placemark.locality); // Extract the city name
              NSLog(@"location %@",placemark.name);
              NSLog(@"location %@",placemark.ocean);
              NSLog(@"location %@",placemark.postalCode);
              NSLog(@"location %@",placemark.subLocality);

              NSLog(@"location %@",placemark.location);
              //Print the location to console
              NSLog(@"I am currently at %@",locatedAt);


              _City.text=[placemark.addressDictionary objectForKey:@"City"];
              [locationManager stopUpdatingLocation];
          }

 ];
}





#pragma mark - CLLocationManagerDelegate

请添加这两种方法

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation

希望这项工作

谢谢

答案 2 :(得分:1)

在调用startUpdatingLocation之前,您需要先调用函数来询问权限。

locationManager = [[CLLocationManager alloc] init]; 
locationManager.desiredAccuracy = kCLLocationAccuracyBest; 
locationManager.delegate = self;
[locationManager requestWhenInUseAuthorization]; 
[locationManager startUpdatingLocation];

答案 3 :(得分:1)

You need to add
"NSLocationAlwaysUsageDescription"
"NSLocationWhenInUseUsageDescription" key in
Info.plist with a message to be displayed.

In .h file
<CLLocationManagerDelegate>
{
 CLGeocoder *geoCoder;
 CLLocationManager *locationManager;
 CLPlacemark *placeMark;
}
@property (weak, nonatomic) IBOutlet MKMapView *mapView;

and .m file

in viewDidLoad Method

_mapView.showsUserLocation = YES;
[self geoLocation];

after that we have to call Delegate methods for CLLocationManager
-(void)geoLocation
{
  geoCoder = [[CLGeocoder alloc] init];
if (locationManager == nil)
  {
    locationManager = [[CLLocationManager alloc] init];
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    locationManager.delegate = self;
    [locationManager requestAlwaysAuthorization];
  }
  [locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
 NSLog(@"didFailWithError: %@", error);
 UIAlertView *errorAlert = [[UIAlertView alloc]
                           initWithTitle:@"Error" message:@"Failed to Get Your Location" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[errorAlert show];
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {

CLLocation *newLocation = [locations lastObject];
//[self getCountryDet:lattitude1];
[geoCoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {

    if (error == nil && [placemarks count] > 0)
    {
        NSString *userLat,*userLong;
        placeMark = [placemarks lastObject];

        userLat = [NSString stringWithFormat:@"%.8f",newLocation.coordinate.latitude];
        userLong= [NSString stringWithFormat:@"%.8f",newLocation.coordinate.longitude];
        // For user address
        NSString *locatedAt = [[placeMark.addressDictionary valueForKey:@"FormattedAddressLines"] componentsJoinedByString:@", "];
        NSString *Address = [[NSString alloc]initWithString:locatedAt];
        NSString *Area = [[NSString alloc]initWithString:placeMark.locality];
        NSString *Country = [[NSString alloc]initWithString:placeMark.country];
        NSString *CountryArea = [NSString stringWithFormat:@"%@, %@", Area,Country];
        NSLog(@"%@",CountryArea);

        // For Zooming Level.
        MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(newLocation.coordinate, 800, 800);
        [self.mapView setRegion:[self.mapView regionThatFits:region] animated:YES];

        // add the Pin annotation
        MKPointAnnotation *pin = [[MKPointAnnotation alloc] init];
        pin.coordinate = newLocation.coordinate;
        pin.title = Address;
        pin.subtitle = Area;
        [self.mapView addAnnotation:pin];

    } else {
        NSLog(@"%@", error.debugDescription);
    }
}];
// Turn off the location manager to save power.
[manager stopUpdatingLocation];
}

答案 4 :(得分:0)

  // IN this code use for get current location address 

  // Create Objet :

    1)create object: CLGeocoder *geocoder;


    2) add viewDidLoad method :


      geocoder = [[CLGeocoder alloc] init];


 -(void)locationManager:(CLLocationManager *)manager didUpdateLocations: (NSArray *)locations

{ CLLocation *newLocation = [locations lastObject];

NSLog(@"didUpdateToLocation: %@", newLocation);
CLLocation *currentLocation = newLocation;

[locationManager stopUpdatingLocation];

if (currentLocation != nil)
{
    self.longitude.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude];
    self.latitude.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude];
}

NSLog(@"Resolving the Address");
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error)
 {

     NSLog(@"Found placemarks current: %@, error: %@", placemarks, error);
     if (error == nil && [placemarks count] > 0)
     {

       //  placemark = [placemarks lastObject];
         placemark = [placemarks objectAtIndex:0];


         NSString *name = [NSString stringWithFormat:@"%@,%@,%@,%@,%@",
                         placemark.subLocality,
                         placemark.locality,
                         placemark.administrativeArea,placemark.postalCode,
                         placemark.country];


         self.addressview.text=name;
     }


     else
     {
         NSLog(@"%@", error.debugDescription);
     }
 } ];

}