繁体   English   中英

在iOS Objective-C中未调用位置管理器委托

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

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

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 如果要“始终”更新位置,则必须使用(自iOS 8起)。

其他几件事:

  • 您应该在委托中实现locationManager:didChangeAuthorizationStatus:因为这是CLLocationManager会告诉您用户是否授予位置信息权限的地方。
  • 除非您支持iOS 7或更早版本,否则无需您的respondsToSelector检查。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM