如何在 iOS 中使用 CLLocationManager 获取当前位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21554127/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 23:20:56  来源:igfitidea点击:

How to get current location using CLLocationManager in iOS

iosiphoneobjective-c

提问by Rajesh Loganathan

I can already find the current location using latitude and longitude, but I would also like to be able to find the current location given a zip code.

我已经可以使用纬度和经度找到当前位置,但我也希望能够找到给定邮政编码的当前位置。

Here is what I have so far:

这是我到目前为止所拥有的:

.h

。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

.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];


    NSString *latitude = [NSString stringWithFormat:@"%f", coordinate.latitude];
    NSString *longitude = [NSString stringWithFormat:@"%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 = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude];
    lable2.text = [NSString stringWithFormat:@"%.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 = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude];
    lable2.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

回答by Rajesh Loganathan

Step 1:Import MobileCoreServicesframework in .hFile

第 1 步:MobileCoreServices.h文件中导入框架

#import <MobileCoreServices/MobileCoreServices.h>

#import <MobileCoreServices/MobileCoreServices.h>

Step 2:Add delegate CLLocationManagerDelegate

第 2 步:添加委托CLLocationManagerDelegate

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

Step 3:Add this code in class file

第 3 步:在类文件中添加此代码

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

Step 4:Method to get location

第 4 步:获取位置的方法

//------------ 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);
             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);
         }
         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);
          ------*/
     }];
}

回答by Hardik Thakkar

Here is a code to get user current location using block

这是使用块获取用户当前位置的代码

1) #import <CoreLocation/CoreLocation.h>

1) #import <CoreLocation/CoreLocation.h>

2) <CLLocationManagerDelegate>

2) <CLLocationManagerDelegate>

3) in .h file

3)在.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) NSString *current_Lat;
@property (nonatomic,strong) NSString *current_Long;

4) in .m file

4) 在 .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 = [NSString stringWithFormat:@"%f",currentLoc.coordinate.latitude];
    _current_Long = [NSString stringWithFormat:@"%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) Call function

5) 通话功能

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

6) And add below line to .plist

6)并将以下行添加到.plist

Any one or both of below keys needs to be added in Info.plist file.

需要在 Info.plist 文件中添加以下任何一个或两个键。

NSLocationWhenInUseUsageDescription
NSLocationAlwaysUsageDescription

回答by Ajay

You can call Google APIs Mapsservice to get the location using zipcode:

您可以调用Google API 地图服务以使用邮政编码获取位置:

Just enter your zipcode in address={your zipcode}.

只需在address={your zipcode}.

回答by Jagveer Singh

if location permissions not asking when you first launch then you cant get your current location .

如果您第一次启动时没有询问位置权限,那么您将无法获得当前位置。

iOS8 has got us major API changes with the LocationsServices

iOS8 对 LocationsServices 进行了重大的 API 更改

Assuming [CLLocationManager locationServicesEnabled] return YES,

假设 [CLLocationManager locationServicesEnabled] 返回 YES,

With the First Launch of the iOS App [both iOS7 and iOS8] - locationMangers(CLLocationManager)

随着 iOS 应用的首次发布 [iOS7 和 iOS8] - locationMangers(CLLocationManager)