我正在尝试开发一款可以获取每个位置手机移动位置属性的应用。 这是我现在获取设备位置的代码
ViewController.h
@interface ViewController : UIViewController <CLLocationManagerDelegate, CBCentralManagerDelegate, AVAudioRecorderDelegate, AVAudioPlayerDelegate>
{
CLLocationManager *locationManager;
CMMotionManager *motionManager;
}
@property(nonatomic, strong) CLLocationManager *locationManager;
@end
ViewController.m
locationManager = [[CLLocationManager alloc] init];
- (void)startAllDataRec
{
[self getLocation];
}
- (void)getLocation
{
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
if ([locationManager respondsToSelector:@selector(requestAlwaysAuthorization)])
{
[locationManager requestAlwaysAuthorization];
}
//Checking authorization status
if (![CLLocationManager locationServicesEnabled] && [CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied)
{
NSLog(@"you are denied a permission");
}
else
{
//Location Services Enabled, let's start location updates
[locationManager startUpdatingLocation];
}
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(@"didFailWithError: %@", error);
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(@"didUpdateToLocation: %@", newLocation);
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
mLat = currentLocation.coordinate.latitude;
mLon = currentLocation.coordinate.longitude;
mSpeed = currentLocation.speed;
mAlt = currentLocation.altitude;
mCourse = currentLocation.course;
NSLog(@"lat lon speed alt course = %f, %f, %f, %f, %f", mLat, mLon, mSpeed, mAlt, mCourse);
dispatch_async(dispatch_get_main_queue(), ^{
self.speedLbl.text = [NSString stringWithFormat:@"%f", mSpeed];
});
}
else{NSLog(@"current location is nil");};
}
问题是,代理人在任何时候都没有被调用,换句话说即使我提供访问权限也不会被触发 有什么我缺少的,需要先被调用吗?
答案 0 :(得分:0)
最可能的原因 - 因为你没有提到它 - 是你的应用程序的Info.plist文件中没有NSLocationAlwaysUsageDescription
。如果您想要“始终”更新位置,这是必需的(因为iOS 8)。
其他一些事情:
locationManager:didChangeAuthorizationStatus:
,因为CLLocationManager
会告诉您用户是否有权获取位置信息。respondsToSelector
检查是不必要的。