在后台线程上接收CLLocation更新

时间:2010-10-22 20:04:23

标签: iphone core-location cllocationmanager

我正在尝试使用iPhone SDK实现(非并发)NSOperation以进行位置更新。 NSOperation子类的“肉”是这样的:

- (void)start {
    // background thread set up by the NSOperationQueue
    assert(![NSThread isMainThread]);

    if ([self isCancelled]) {
        return;
    }

    self->locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;
    locationManager.desiredAccuracy = self->desiredAccuracy;
    locationManager.distanceFilter = self->filter;
    [locationManager startUpdatingLocation];

    [self willChangeValueForKey:@"isExecuting"];
    self->acquiringLocation = YES;
    [self didChangeValueForKey:@"isExecuting"];
}

- (void)cancel {
    if ( ! self->cancelled ) {
        [self willChangeValueForKey:@"isCancelled"];
        self->cancelled = YES;
        [self didChangeValueForKey:@"isCancelled"];

        [self stopUpdatingLocation];
    }
}

- (BOOL)isExecuting {
    return self->acquiringLocation == YES;
}

- (BOOL)isConcurrent {
    return NO;
}

- (BOOL)isFinished {
    return self->acquiringLocation == NO;
}

- (BOOL)isCancelled {
    return self->cancelled;
}



- (void)stopUpdatingLocation {
    if (self->acquiringLocation) {
        [locationManager stopUpdatingLocation];

        [self willChangeValueForKey:@"isExecuting"];
        [self willChangeValueForKey:@"isFinished"];
        self->acquiringLocation = NO;  
        [self didChangeValueForKey:@"isExecuting"];
        [self didChangeValueForKey:@"isFinished"];
    }
    locationManager.delegate = nil;
}


- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    assert(![NSThread isMainThread]);

    // ... I omitted the rest of the code from this post

    [self stopUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)theError {
    assert(![NSThread isMainThread]);
    // ... I omitted the rest of the code from this post
}

现在,在主线程上,我创建了一个此操作的实例,并将其添加到NSOperationQueue中。调用start方法,但不会调用-locationManager:...委托方法。我不明白为什么他们永远不会被召唤。

我确实使接口符合<CLLocationManagerDelegate>协议。我让NSOperationQueue管理这个操作的线程,所以它应该符合CLLocationManagerDelegate文档:

  

从您启动相应位置服务的线程调用委托对象的方法。该线程本身必须有一个活动的运行循环,就像在应用程序的主线程中找到的那样。

我不知道还有什么可以尝试的。也许它正盯着我的脸......任何帮助都表示赞赏。

提前致谢!

1 个答案:

答案 0 :(得分:6)

您缺少“活动运行循环”部分。在开始方法结束时添加:

while (![self isCancelled])
  [[NSRunLoop currentRunLoop] runUntilDate:someDate];