右键info.plist open as --> 源代码将以下代码添加到<dict>...</dict>
<key>NSLocationAlwaysUsageDescription</key>
<string>App would like to use your location.</string>
<key>NSLocationUsageDescription</key>
<string>I need Location</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>App would like to use your location.</string>
<key>UIMainStoryboardFile</key>
导入
#import <CoreLocation/CoreLocation.h>
#import <MobileCoreServices/MobileCoreServices.h>
然后进入 viewcontroller.h 添加 CLLocationManagerDelegate
在 viewcontroller.m 文件中添加这个方法。
-(void)getCurrentLocation{
self.locationManager = [[CLLocationManager alloc] init];
if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
[self.locationManager requestWhenInUseAuthorization];
[self.locationManager requestAlwaysAuthorization];
}
self.locationManager.delegate = self;
self.locationManager.distanceFilter = 10;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[self.locationManager startUpdatingLocation];
}
然后调用CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manage
didUpdateLocations:(NSArray *)locations
{
CLLocation *currentAction = [locations objectAtIndex:0];
CLLocation *crnLoc = [locations lastObject];
[self.locationManager stopUpdatingLocation];
CLGeocoder *geocoder = [[CLGeocoder alloc] init] ;
CLLocation* location = [locations lastObject];
NSDate* eventDate = location.timestamp;
NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
if (abs(howRecent) < 15.0) {
// If the event is recent, do something with it.
NSLog(@"latitude~~~: %+.8f, longitude~~~: %+.8f\n",
location.coordinate.latitude,
location.coordinate.longitude);
self.latitudeLabel.text=[NSString stringWithFormat:@"%.8f",
crnLoc.coordinate.latitude];
self.longitudeLabel.text=[NSString stringWithFormat:@"%.8f",
crnLoc.coordinate.longitude];
}
self.latitudeLabel.text=[NSString stringWithFormat:@"%.8f",
crnLoc.coordinate.latitude];
self.longitudeLabel.text=[NSString stringWithFormat:@"%.8f",
crnLoc.coordinate.longitude];
[geocoder reverseGeocodeLocation:currentAction
completionHandler:^(NSArray *placemarks, NSError *error)
{
if (!(error))
{
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSString *locatedAt = [[placemark.addressDictionary
valueForKey:@"FormattedAddressLines"]
componentsJoinedByString:@", "];
NSString *Address = [[NSString alloc]initWithString:locatedAt];
NSLog(@"Adress %@",Address);
}
else
{
NSLog(@"\n Current Location Not Detected \n");
return;
}
}];
}
希望此代码对您有所帮助。