简体   繁体   English

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

[英]Get User Current location using CLLocation in IOS

I want to get the user current location & address which I did using the CLLocationManager and added the core location framework. 我想获取使用CLLocationManager并添加核心位置框架的用户当前位置和地址。 But the response is nothing. 但是,回应无济于事。 Please share your comments. 请分享您的评论。

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

and the delegates are 代表们是

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

You need to add 您需要添加
"NSLocationAlwaysUsageDescription"
"NSLocationWhenInUseUsageDescription" key in "NSLocationWhenInUseUsageDescription"
Info.plist with a message to be displayed. Info.plist带有要显示的消息。

Check My code you can get address from current location 选中我的代码,您可以从当前位置获取地址

- (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

Please add this two method 请添加这两种方法

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

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

Hope This work 希望这项工作

Thank you 谢谢

you need to call function to ask permission first before calling startUpdatingLocation . 您需要先调用function来请求权限,然后再调用startUpdatingLocation

locationManager = [[CLLocationManager alloc] init]; 
locationManager.desiredAccuracy = kCLLocationAccuracyBest; 
locationManager.delegate = self;
[locationManager requestWhenInUseAuthorization]; 
[locationManager startUpdatingLocation];
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];
}
  // 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]; {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);
     }
 } ];

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM