Comment get l'location actuel en utilisant CLLocationManager dans iOS

Je peux déjà find l'location actuel en utilisant la latitude et la longitude, mais je voudrais aussi pouvoir find l'location actuel donné un code postal.

Voici ce que j'ai jusqu'ici:

.h

#import <MapKit/MapKit.h> #import <UIKit/UIKit.h> #import <CoreLocation/CoreLocation.h> @interface ViewController : UIViewController<CLLocationManagerDelegate> { CLLocationManager *locationManager; CLLocation *currentLocation; IBOutlet UILabel *label1; IBOutlet UILabel *lable2; } @property (weak, nonatomic) IBOutlet MKMapView *myMapview; @property (weak, nonatomic) IBOutlet UILabel *label2; @property (weak, nonatomic) IBOutlet UILabel *lable1; @end 

.m

 #import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. locationManager = [[CLLocationManager alloc]init]; locationManager.delegate = self; locationManager.distanceFilter = kCLDistanceFilterNone; locationManager.desiredAccuracy = kCLLocationAccuracyBest; [locationManager startUpdatingLocation]; _myMapview.showsUserLocation = YES; [self->locationManager startUpdatingLocation]; CLLocation *location = [locationManager location]; CLLocationCoordinate2D coordinate = [location coordinate]; NSSsortingng *latitude = [NSSsortingng ssortingngWithFormat:@"%f", coordinate.latitude]; NSSsortingng *longitude = [NSSsortingng ssortingngWithFormat:@"%f", coordinate.longitude]; //NSLog(@”dLatitude : %@”, latitude); //NSLog(@”dLongitude : %@”,longitude); NSLog(@"MY HOME :%@", latitude); NSLog(@"MY HOME: %@ ", longitude); } #pragma mark CLLocationManager Delegate - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations { currentLocation = [locations objectAtIndex:0]; [locationManager stopUpdatingLocation]; [self->locationManager stopUpdatingLocation]; NSLog(@"my latitude :%f",currentLocation.coordinate.latitude); NSLog(@"my longitude :%f",currentLocation.coordinate.longitude); label1.text = [NSSsortingng ssortingngWithFormat:@"%.8f", currentLocation.coordinate.longitude]; lable2.text = [NSSsortingng ssortingngWithFormat:@"%.8f", currentLocation.coordinate.latitude]; NSLog(@"Detected Location : %f, %f", currentLocation.coordinate.latitude, currentLocation.coordinate.longitude); CLGeocoder *geocoder = [[CLGeocoder alloc] init] ; [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) { if (error) { NSLog(@"Geocode failed with error: %@", error); return; } NSLog(@"Monday"); CLPlacemark *placemark = [placemarks objectAtIndex:0]; NSLog(@"placemark.ISOcountryCode %@",placemark.ISOcountryCode); }]; } - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { NSLog(@"didUpdateToLocation: %@", newLocation); CLLocation *currentLocation = newLocation; if (currentLocation != nil) { label1.text = [NSSsortingng ssortingngWithFormat:@"%.8f", currentLocation.coordinate.longitude]; lable2.text = [NSSsortingng ssortingngWithFormat:@"%.8f", currentLocation.coordinate.latitude]; } } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end 

Étape 1: import de l' MobileCoreServices dans un file .h

#import <MobileCoreServices/MobileCoreServices.h>

Étape 2: Ajouter un délégué CLLocationManagerDelegate

 @interface yourViewController : UIViewController<CLLocationManagerDelegate> { CLLocationManager *locationManager; CLLocation *currentLocation; } 

Étape 3: Ajoutez ce code dans le file de class

 - (void)viewDidLoad { [super viewDidLoad]; [self CurrentLocationIdentifier]; // call this method } 

Étape 4: Méthode pour get l'location

 //------------ Current Location Address----- -(void)CurrentLocationIdentifier { //---- For getting current gps location locationManager = [CLLocationManager new]; locationManager.delegate = self; locationManager.distanceFilter = kCLDistanceFilterNone; locationManager.desiredAccuracy = kCLLocationAccuracyBest; [locationManager startUpdatingLocation]; //------ } - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations { currentLocation = [locations objectAtIndex:0]; [locationManager stopUpdatingLocation]; CLGeocoder *geocoder = [[CLGeocoder alloc] init] ; [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) { if (!(error)) { CLPlacemark *placemark = [placemarks objectAtIndex:0]; NSLog(@"\nCurrent Location Detected\n"); NSLog(@"placemark %@",placemark); NSSsortingng *locatedAt = [[placemark.addressDictionary valueForKey:@"FormattedAddressLines"] componentsJoinedBySsortingng:@", "]; NSSsortingng *Address = [[NSSsortingng alloc]initWithSsortingng:locatedAt]; NSSsortingng *Area = [[NSSsortingng alloc]initWithSsortingng:placemark.locality]; NSSsortingng *Country = [[NSSsortingng alloc]initWithSsortingng:placemark.country]; NSSsortingng *CountryArea = [NSSsortingng ssortingngWithFormat:@"%@, %@", Area,Country]; NSLog(@"%@",CountryArea); } else { NSLog(@"Geocode failed with error %@", error); NSLog(@"\nCurrent Location Not Detected\n"); //return; CountryArea = NULL; } /*---- For more results placemark.region); placemark.country); placemark.locality); placemark.name); placemark.ocean); placemark.postalCode); placemark.subLocality); placemark.location); ------*/ }]; } 

Voici un code pour get l'location actuel de l'user en utilisant le bloc

1) #import <CoreLocation/CoreLocation.h>

2) <CLLocationManagerDelegate>

3) dans le file .h

 //Location typedef void(^locationBlock)(); //Location -(void)GetCurrentLocation_WithBlock:(void(^)())block; @property (nonatomic, strong) locationBlock _locationBlock; @property (nonatomic,copy)CLLocationManager *locationManager; @property (nonatomic)CLLocationCoordinate2D coordinate; @property (nonatomic,strong) NSSsortingng *current_Lat; @property (nonatomic,strong) NSSsortingng *current_Long; 

4) dans le file .m

 #pragma mark - CLLocationManager -(void)GetCurrentLocation_WithBlock:(void(^)())block { self._locationBlock = block; _locationManager = [[CLLocationManager alloc] init]; [_locationManager setDelegate:self]; [_locationManager setDistanceFilter:kCLDistanceFilterNone]; [_locationManager setDesiredAccuracy:kCLLocationAccuracyBest]; if (IS_OS_8_OR_LATER) { if ([_locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) { [_locationManager requestWhenInUseAuthorization]; [_locationManager requestAlwaysAuthorization]; } } [_locationManager startUpdatingLocation]; } - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations { CLLocation *currentLoc=[locations objectAtIndex:0]; _coordinate=currentLoc.coordinate; _current_Lat = [NSSsortingng ssortingngWithFormat:@"%f",currentLoc.coordinate.latitude]; _current_Long = [NSSsortingng ssortingngWithFormat:@"%f",currentLoc.coordinate.longitude]; NSLog(@"here lat %@ and here long %@",_current_Lat,_current_Long); self._locationBlock(); [_locationManager stopUpdatingLocation]; _locationManager = nil; } - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error { } 

5) fonction d'appel

 - (void)viewDidLoad { [super viewDidLoad]; [self GetCurrentLocation_WithBlock:^{ NSLog(@"Lat ::%f,Long ::%f",[self.current_Lat floatValue],[self.current_Long floatValue]); }]; } 

6) Et ajoutez ci-dessous la ligne à .plist

Une ou les deux keys ci-dessous doivent être ajoutées dans le file Info.plist.

 NSLocationWhenInUseUsageDescription NSLocationAlwaysUsageDescription 

Si les permissions de localization ne vous requestnt pas lors du premier lancement, vous ne pouvez pas get votre position actuelle.

iOS8 nous a apporté des modifications majeures de l'API avec LocationsServices

En supposant que [CLLocationManager locationServicesEnabled] renvoie YES,

Avec le premier lancement de l'application iOS [iOS7 et iOS8] – locationMangers (CLLocationManager)

Vous pouvez appeler le service Google Maps Maps pour get l'location à l'aide du code postal:

Il suffit d'entrer votre code postal dans l' address={your zipcode} .