ios objective-c 中未调用位置管理器委托

Location manager delegate is not being called in ios objective-c

我正在尝试开发一个可以获取每个位置 phone 移动的位置属性的应用程序。 这是我现在拥有的用于获取设备位置的代码

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");};
}

问题是,任何时候都不会调用委托,换句话说,即使我授予访问权限,它也不会被触发 有什么我遗漏的,需要先打电话吗?

最可能的原因——因为你没有提到它——是你的应用程序的 Info.plist 文件中没有 NSLocationAlwaysUsageDescription。如果您想要 "always" 位置更新,这是必需的(自 iOS 8 起)。

其他几件事:

  • 您应该在委托中实现 locationManager:didChangeAuthorizationStatus:,因为那是 CLLocationManager 会告诉您用户是否允许获取位置信息的地方。
  • 您的 respondsToSelector 检查是不必要的,除非您支持 iOS 7 或更早版本。