How Can I Get Current Location on iOS? [duplicate]

耗尽温柔 提交于 2019-11-29 18:14:50

You are doing [locationManager startUpdatingLocation]; before setting its delegate

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

[locationManager startUpdatingLocation];

And implement its delegate method

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

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

}

For getting current location as well as its coordinates,you just have to do only this in your viewDidLoad method :

- (void)viewDidLoad {
  [super viewDidLoad];
  locationManager = [[CLLocationManager alloc] init];
  locationManager.delegate = self;
  locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
  locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
  [locationManager startUpdatingLocation];
}

And about updating location,use this method :

    - (void)locationManager:(CLLocationManager *)manager
        didUpdateToLocation:(CLLocation *)newLocation
               fromLocation:(CLLocation *)oldLocation{
// your code here...
}

You should read the documentation provided in the Location Awareness Programming Guide.

Specifically, when you ask for the current location, the system returns the last known location right away so you can do something useful with it. If you don't care about past locations, you can discard it and only use more recent location information by looking at the timestamp property of the CLLocation returned to determine how recent it is.

You should really read the CLLocationManager documentation.

Wat you are doing will not work, since it will take some time determine the device location. Therefor you will need to wait until the CLLocationManager notifies you that a location has been determent.

You will need to implement the CLLocationManagerDelegate which will tell you if a location is determent or if the location determination failed.

Also you should also check if location can be determent with:

if ([CCLocationManager locationServicesEnabled]) {
    // The location services are available.
}

You should also check wether you are authorize to use the location services with [CCLocationManager authorizationStatus].

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!