didUpdateLocations未被调用

时间:2014-10-03 11:54:37

标签: ios objective-c xcode swift cllocationmanager

我将对象设置为locationManager的委托,并调用didChangeAuthorizationStatus方法,这样做:

func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
    if status == CLAuthorizationStatus.AuthorizedWhenInUse {
        self.locationManager.startUpdatingLocation()
    }
}

我也有这种方法,在此之后永远不会被调用:

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
    if locations.count == 0 {
        return
    }

    //Do stuff
}

有关为何可能不会被调用的任何想法?我认为被解除分配的对象是一个选项,但是当它达到authorizationStatus方法时它也会被释放。

3 个答案:

答案 0 :(得分:16)

这对答案来说已经很晚了,但是当我遇到同样的问题时(didChangeAuthorizationStatus被调用但不是didUpdateLocations),我偶然发现了这一点。当然,这不是代码相关的东西,而是我在没有位置设置的模拟器中进行测试。因此,从未找到该位置,导致didUpdateLocations永远不会被调用。

要解决此问题...在模拟器中转到Debug -> Location-> <choose location>

编辑还应注意,如果未在模拟器中设置位置,locationManager:didFailWithError:将会运行,正如您所期望的那样。

答案 1 :(得分:4)

It's working in iOS 10 and iOS 11 as well,

Create property of CLLocationManager using strong and add CLLocationManagerDelegate

@property (strong, nonatomic) CLLocationManager *locationManager;

Add below properties into your info.plist file

Privacy - Location When In Use Usage Description
Privacy - Location Always Usage Description
Privacy - Location Usage Description

Add below method in to your .m file

-(void)getCurrentLocation
{
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate=self;
    self.locationManager.desiredAccuracy=kCLLocationAccuracyBest;
    self.locationManager.distanceFilter=kCLDistanceFilterNone;
    [self.locationManager requestWhenInUseAuthorization];
    [self.locationManager startMonitoringSignificantLocationChanges];
    [self.locationManager startUpdatingLocation];
}

and just call [self getCurrentLocation] method.

答案 2 :(得分:0)

以下是我应用的摘录:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
    ...
    locationManager.delegate = self
    locationManager.activityType = CLActivityType.Fitness
    locationManager.distanceFilter = 10   // 10m
    locationManager.requestAlwaysAuthorization()

    // get current location
    if CLLocationManager.authorizationStatus() == CLAuthorizationStatus.Authorized {
        locationManager.startUpdatingLocation()
    }
}

func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
    if status == .Authorized {
        locationManager.startUpdatingLocation()
    }
}

您必须将NSLocationAlwaysUsageDescription密钥放在Info.plist中,并将值设置为授权问题。这是iOS 8的要求。