我更喜欢使用 MKMapView 内部使用的 CLLocationManager,所以如果您不需要使用地图,只需使用位置管理器中的以下代码即可。
locationManager = [[CLLocationManager alloc] init];
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.delegate = self;
[locationManager startUpdatingLocation];
只是不要忘记将 locationManager 实例存储在您的类中的某个位置,您可以像这样实现委托。
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
NSLog(@"Error detecting location %@", error);
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
CLLocation* location = (CLLocation*)locations.lastObject;
NSLog(@"Longitude: %f, Latitude: %f", location.coordinate.longitude, location.coordinate.latitude);
}
编辑
您可以使用 Apple 的地理编码器根据用户的位置获取用户的地址
// Use Apple's Geocoder to figure the name of the place
CLGeocoder* geoCoder = [[CLGeocoder alloc] init];
[geoCoder reverseGeocodeLocation:location completionHandler: ^(NSArray* placemarks, NSError* error) {
if (error != nil) {
NSLog(@"Error in geo coder: %@", error);
}
else {
if (placemarks.count == 0) {
NSLog(@"The address couldn't be found");
}
else {
// Get nearby address
CLPlacemark* placemark = placemarks[0];
// Get the string address and store it
NSString* locatedAt = [[placemark.addressDictionary valueForKey:@"FormattedAddressLines"] componentsJoinedByString:@", "];
location.name = locatedAt;
NSLog(@"The address is: %@", locatedAt);
}
}
}];