5

I am trying to make use of CLLocationManager in an NSOperation. As part of this I require the ability to startUpdatingLocation then wait until a CLLocation is received before completing the operation.

At present I have done the following, however the delegate method never seems to be called. Please can someone advise what the issue is?

- (void)main
{
    @autoreleasepool {
        if (self.isCancelled)
            return;

        // Record the fact we have not found the location yet
        shouldKeepLooking = YES;

        // Setup the location manager
        NSLog(@"Setting up location manager.");
        CLLocationManager *locationManager = [[CLLocationManager alloc] init];
        locationManager.delegate = self;
        locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        [locationManager startUpdatingLocation];

        while (shouldKeepLooking) {

            if (self.isCancelled)
                return;

            // Do some other logic...
        }
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    // None of this ever seems to be called (despite updating the location)
    latestLocation = [locations lastObject];
    [manager stopUpdatingLocation];
    shouldKeepLooking = NO;
}
  • I don't like the busy waiting mechanism here. It was better if you were letting the runloop run until the location was updated. – Ramy Al Zuhouri Aug 25 '13 at 12:38
  • How can I do this? I would prefer to have this setup too. I was not aware of how to wait until the location was updated though. –  Aug 25 '13 at 12:40
  • why are you doing that in the main by the way? It may be may the issue. – Gabriele Petronella Aug 25 '13 at 12:41
  • I was following this tutorial: http://www.cimgf.com/2008/02/16/cocoa-tutorial-nsoperation-and-nsoperationqueue/ Is there a better way to do it? –  Aug 25 '13 at 12:46
  • 1
    Why are you trying to do it all in a background thread? Get the location in the main thread and then do the resultant processing on your background thread. – Wain Aug 25 '13 at 12:56
  • 1
    @TheCrazyChimp Why are you doing this in an operation at all? Location manager is already asynchronous and this seems ill-suited for an operation. You can do it, but why? – Rob Aug 25 '13 at 17:35

4 Answers4

5

Going back to the runloop discussion, this is how I generally solve that in my base NSOperation implementation:

// create connection and keep the current runloop running until
// the operation has finished. this allows this instance of the operation
// to act as the connections delegate
_connection = [[NSURLConnection alloc] initWithRequest:[self request]
                                              delegate:self];
while(!self.isFinished) {
    [[NSRunLoop currentRunLoop] runUntilDate:[NSDate distantFuture]];
}

I key off of isFinished, which I keep updated through setters for isCancelled and isFinished. Here's the isCancelled setter as an example:

- (void)setIsCancelled:(BOOL)isCancelled {
    _isCancelled = isCancelled;
    if (_isCancelled == YES) {
        self.isFinished = YES;
    }
}

That said, I second some of the questions about why this is necessary. If you don't need to kick something off until a location is found, why not just fire up your location manager on the main thread, wait for the appropriate delegate callback and then kick off the background operation?

Update: updated solution

While the original answer generally stands, I've fully implement a solution and it does require a slight change to how you manage the run loop. That said, all code is available on GitHub - https://github.com/nathanhjones/CLBackgroundOperation. Here is a detailed explanation of the approach.

Tl;dr

Change

[[NSRunLoop currentRunLoop] runUntilDate:[NSDate distantFuture]];

to

[[NSRunLoop currentRunLoop] runMode:NSRunLoopCommonModes
                         beforeDate:[NSDate distantFuture]];

Details

Within your operations interface define the following three properties. We'll be indicating that these operations are concurrent thus we'll manage their state manually. In the solution on GitHub these are part of NJBaseOperation.

@property(nonatomic,assign,readonly) BOOL isExecuting;
@property(nonatomic,assign,readonly) BOOL isFinished;
@property(nonatomic,assign,readonly) BOOL isCancelled;

Within your operations implementation you'll want to make those readwrite like so:

@interface NJBaseOperation ()

@property(nonatomic,assign,readwrite) BOOL isExecuting;
@property(nonatomic,assign,readwrite) BOOL isFinished;
@property(nonatomic,assign,readwrite) BOOL isCancelled;

@end

Next, you'll want to synthesize the three properties you defined above so that you can override the setters and use them to manage your operations state. Here's what I generally use, but sometimes there are some additional statements added to the setIsFinished: method depending on my needs.

- (void)setIsExecuting:(BOOL)isExecuting {
    _isExecuting = isExecuting;
    if (_isExecuting == YES) {
        self.isFinished = NO;
    }
}

- (void)setIsFinished:(BOOL)isFinished {
    _isFinished = isFinished;
    if (_isFinished == YES) {
        self.isExecuting = NO;
    }
}

- (void)setIsCancelled:(BOOL)isCancelled {
    _isCancelled = isCancelled;
    if (_isCancelled == YES) {
        self.isFinished = YES;
    }
}

Lastly, just so that we don't have to manually send the KVO notifications we'll implement the following method. This works because our properties are named isExecuting, isFinished and isCancelled.

+ (BOOL) automaticallyNotifiesObserversForKey:(NSString *)key {
    return YES;
}

Now that the the operations foundation is taken care of it's time to knockout the location stuff. You'll want to override main and within it fire up your location manager and instruct the current run loop to keep running until you tell it otherwise. This ensures that your thread is around to receive the location delegate callbacks. Here's my implementation:

- (void)main {

    if (_locationManager == nil) {
        _locationManager = [[CLLocationManager alloc] init];
        _locationManager.delegate = self;
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        [_locationManager startUpdatingLocation];
    }

    while(!self.isFinished) {
        [[NSRunLoop currentRunLoop] runMode:NSRunLoopCommonModes
                                 beforeDate:[NSDate distantFuture]];
    }
}

You should receive a delegate callback at which point you can do some work based on location and then finish the operation. Here's my implementation that counts to 10,000 and then cleans up.

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    NSLog(@"** Did Update Location: %@", [locations lastObject]);
    [_locationManager stopUpdatingLocation];

    // do something here that takes some length of time to complete
    for (int i=0; i<10000; i++) {
        if ((i % 10) == 0) {
            NSLog(@"Loop %i", i);
        }
    }

    self.isFinished = YES;
}

The source on GitHub includes a dealloc implementation, which simply logs that it's being called and also observes changes to the operationCount of my NSOperationQueue and logs the count - to indicating when it drops back to 0. Hope that helps. Let me know if you've got questions.

Nathan Jones
  • 1,836
  • 14
  • 13
  • Have you tried this in conjunction with `CLLocationManager`? This pattern works in conjunction with `NSURLConnection`, but it appears that `CLLocationManager` must be attaching some source to the run loop, and thus `distantFuture` becomes, quite literally, the distant future. – Rob Aug 25 '13 at 18:31
  • I have not used it specifically with `CLLocationManager`. However, this instructs the current runloop to run until 'finished'. There should be no issue performing core location tasks on a background thread provided the thread has an active runloop. Perhaps there is an ordering issue here? Here is some additional information on runloop management - [link]https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Multithreading/RunLoopManagement/RunLoopManagement.html. – Nathan Jones Aug 25 '13 at 23:13
  • You misunderstand me. The problem with this technique is not that location services won't work (because it will), but rather because of something that location services is doing (probably adding some source to the run loop), you'll never return from your call to `runUntilDate`, and thus `main`/`start` won't complete, and you'll never release the memory. Try your code with `CLLocationManager`, putting a `NSLog` after your `while` loop in `main`/`start` or, better, in `dealloc` for the operation, and you'll see what I mean. Everything will appear to work, but you'll leak your `NSOperation`. – Rob Aug 26 '13 at 01:12
  • You could, though, remedy this by using `[NSDate dateWithTimeIntervalSinceNow:1.0]`, or something like that, instead of `[NSDate distantFuture]`. This will assure that `main` will now complete when the operation `isFinished` and your operation will get released properly, but that doesn't feel right either. – Rob Aug 26 '13 at 01:21
  • While using `runUntilDate:` does not seem to work, tinkering with the run loop modes solves the problem. The operation is removed from the queue upon completion and operation is deallocated. I've created a test project and will update my answer shortly. – Nathan Jones Aug 26 '13 at 19:19
4

I think you have two options.

  1. Create a separate thread, with its own run loop, for location services:

    #import "LocationOperation.h"
    #import <CoreLocation/CoreLocation.h>
    
    @interface LocationOperation () <CLLocationManagerDelegate>
    
    @property (nonatomic, readwrite, getter = isFinished)  BOOL finished;
    @property (nonatomic, readwrite, getter = isExecuting) BOOL executing;
    
    @property (nonatomic, strong) CLLocationManager *locationManager;
    
    @end
    
    @implementation LocationOperation
    
    @synthesize finished  = _finished;
    @synthesize executing = _executing;
    
    - (id)init
    {
        self = [super init];
        if (self) {
            _finished = NO;
            _executing = NO;
        }
        return self;
    }
    
    - (void)start
    {
        if ([self isCancelled]) {
            self.finished = YES;
            return;
        }
    
        self.executing = YES;
    
        [self performSelector:@selector(main) onThread:[[self class] locationManagerThread] withObject:nil waitUntilDone:NO modes:[[NSSet setWithObject:NSRunLoopCommonModes] allObjects]];
    }
    
    - (void)main
    {
        [self startStandardUpdates];
    }
    
    - (void)dealloc
    {
        NSLog(@"%s", __FUNCTION__);
    }
    
    #pragma mark - NSOperation methods
    
    - (BOOL)isConcurrent
    {
        return YES;
    }
    
    - (void)setExecuting:(BOOL)executing
    {
        if (executing != _executing) {
            [self willChangeValueForKey:@"isExecuting"];
            _executing = executing;
            [self didChangeValueForKey:@"isExecuting"];
        }
    }
    
    - (void)setFinished:(BOOL)finished
    {
        if (finished != _finished) {
            [self willChangeValueForKey:@"isFinished"];
            _finished = finished;
            [self didChangeValueForKey:@"isFinished"];
        }
    }
    
    - (void)completeOperation
    {
        self.executing = NO;
        self.finished = YES;
    }
    
    - (void)cancel
    {
        [self stopStandardUpdates];
        [super cancel];
        [self completeOperation];
    }
    
    #pragma mark - Location Manager Thread
    
    + (void)locationManagerThreadEntryPoint:(id __unused)object
    {
        @autoreleasepool {
            [[NSThread currentThread] setName:@"location manager"];
    
            NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
            [runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];
            [runLoop run];
        }
    }
    
    + (NSThread *)locationManagerThread
    {
        static NSThread *_locationManagerThread = nil;
        static dispatch_once_t oncePredicate;
        dispatch_once(&oncePredicate, ^{
            _locationManagerThread = [[NSThread alloc] initWithTarget:self selector:@selector(locationManagerThreadEntryPoint:) object:nil];
            [_locationManagerThread start];
        });
    
        return _locationManagerThread;
    }
    
    #pragma mark - Location Services
    
    - (void)startStandardUpdates
    {
        if (nil == self.locationManager)
            self.locationManager = [[CLLocationManager alloc] init];
    
        self.locationManager.delegate = self;
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        self.locationManager.distanceFilter = 500;
    
        [self.locationManager startUpdatingLocation];
    }
    
    - (void)stopStandardUpdates
    {
        [self.locationManager stopUpdatingLocation];
        self.locationManager = nil;
    }
    
    #pragma mark - CLLocationManagerDelegate
    
    - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
    {
        CLLocation* location = [locations lastObject];
    
        // do whatever you want with the location
    
        // now, turn off location services
    
        if (location.horizontalAccuracy < 50) {
            [self stopStandardUpdates];
            [self completeOperation];
        }
    }
    
    @end
    
  2. Alternatively, even though you're using an operation, you could just run location services on the main thread:

    #import "LocationOperation.h"
    #import <CoreLocation/CoreLocation.h>
    
    @interface LocationOperation () <CLLocationManagerDelegate>
    
    @property (nonatomic, readwrite, getter = isFinished)  BOOL finished;
    @property (nonatomic, readwrite, getter = isExecuting) BOOL executing;
    
    @property (nonatomic, strong) CLLocationManager *locationManager;
    
    @end
    
    @implementation LocationOperation
    
    @synthesize finished  = _finished;
    @synthesize executing = _executing;
    
    - (id)init
    {
        self = [super init];
        if (self) {
            _finished = NO;
            _executing = NO;
        }
        return self;
    }
    
    - (void)start
    {
        if ([self isCancelled]) {
            self.finished = YES;
            return;
        }
    
        self.executing = YES;
    
        [self startStandardUpdates];
    }
    
    #pragma mark - NSOperation methods
    
    - (BOOL)isConcurrent
    {
        return YES;
    }
    
    - (void)setExecuting:(BOOL)executing
    {
        if (executing != _executing) {
            [self willChangeValueForKey:@"isExecuting"];
            _executing = executing;
            [self didChangeValueForKey:@"isExecuting"];
        }
    }
    
    - (void)setFinished:(BOOL)finished
    {
        if (finished != _finished) {
            [self willChangeValueForKey:@"isFinished"];
            _finished = finished;
            [self didChangeValueForKey:@"isFinished"];
        }
    }
    
    - (void)completeOperation
    {
        self.executing = NO;
        self.finished = YES;
    }
    
    - (void)cancel
    {
        [self stopStandardUpdates];
        [super cancel];
        [self completeOperation];
    }
    
    #pragma mark - Location Services
    
    - (void)startStandardUpdates
    {
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            if (nil == self.locationManager)
                self.locationManager = [[CLLocationManager alloc] init];
    
            self.locationManager.delegate = self;
            self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
            self.locationManager.distanceFilter = 500;
    
            [self.locationManager startUpdatingLocation];
        }];
    }
    
    - (void)stopStandardUpdates
    {
        [self.locationManager stopUpdatingLocation];
        self.locationManager = nil;
    }
    
    #pragma mark - CLLocationManagerDelegate
    
    - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
    {
        CLLocation* location = [locations lastObject];
    
        // do whatever you want with the location
    
        // now, turn off location services
    
        if (location.horizontalAccuracy < 50) {
            [self stopStandardUpdates];
            [self completeOperation];
        }
    }
    
    @end
    

I think I'd be inclined to do the second approach (just making sure that I don't do anything too intensive in didUpdateLocations, or if I did, make sure to do it asynchronously), but both of these approaches appear to work.

Another approach is to keep the run loop alive until the operation is finished:

while (![self isFinished]) {
    [[NSRunLoop currentRunLoop] runUntilDate:[NSDate distantFuture]];
}

But this doesn't appear to work in conjunction with CLLocationManager, as runUntilDate doesn't immediately return (it's almost as if CLLocationManager is attaching its own source to the runloop, which prevents it from exiting). I guess you could change the runUntilDate to something a little closer than distantFuture (e.g. [NSDate dateWithTimeIntervalSinceNow:1.0]). Still, I think it's just as easy to run this operation start location services on the main queue, like the second solution above.

Having said that, I'm not sure why you would want to use location manager in an operation at all. It's already asynchronous, so I would just start the location manager from the main queue and call it a day.

Rob
  • 415,655
  • 72
  • 787
  • 1,044
  • I too see no reason for a NSOperation. But IMO, the `cancel` message should be releasing the CLLocationManager object and thus also stop monitoring. – CouchDeveloper Aug 25 '13 at 17:52
  • @CouchDeveloper Agreed. I was focused on the run loop issues, but you're right that you should respond to cancelation events. I've updated my code snippets accordingly. – Rob Aug 25 '13 at 18:28
  • What is the purpose of `[runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];` is it for keeping the runloop alive? – HyBRiD Nov 24 '14 at 10:12
  • Yes, that's precisely why. – Rob Nov 24 '14 at 10:32
1

UIWebView with UIWebViewDelegate method callbacks in an NSOperation

A server I wanted to grab a URL from a server that changes values based upon JavaScript execution from various browsers. So I slapped a dummy UIWebView into an NSOperation and use that to grab out the value I wanted in the UIWebViewDelegate method.

@interface WBSWebViewOperation () <UIWebViewDelegate>

@property (assign, nonatomic) BOOL stopRunLoop;
@property (assign, nonatomic, getter = isExecuting) BOOL executing;
@property (assign, nonatomic, getter = isFinished) BOOL finished;

@property (copy, nonatomic, readwrite) NSURL *videoURL;
@property (strong, nonatomic) UIWebView *webView;

@end



@implementation WBSWebViewOperation

- (id)init
{
    self = [super init];
    if (self) {
        _finished = NO;
        _executing = NO;
    }

    return self;
}

- (id)initWithURL:(NSURL *)episodeURL
{
    self = [self init];
    if (self != nil) {
        _episodeURL = episodeURL;
    }

    return self;
}

- (void)start
{
    if (![self isCancelled]) {
        self.executing = YES;

        [self performSelector:@selector(main) onThread:[NSThread mainThread] withObject:nil waitUntilDone:NO modes:[[NSSet setWithObject:NSRunLoopCommonModes] allObjects]];
    } else {
        self.finished = YES;
    }
}

- (void)main
{
    if (self.episodeURL != nil) {
        NSURLRequest *request = [NSURLRequest requestWithURL:self.episodeURL];
        UIWebView *webView = [[UIWebView alloc] init];
        webView.delegate = self;
        [webView loadRequest:request];

        self.webView = webView;
    }
}



#pragma mark - NSOperation methods

- (BOOL)isConcurrent
{
    return YES;
}

- (void)setExecuting:(BOOL)executing
{
    [self willChangeValueForKey:@"isExecuting"];
    _executing = executing;
    [self didChangeValueForKey:@"isExecuting"];
}

- (void)setFinished:(BOOL)finished
{
    [self willChangeValueForKey:@"isFinished"];
    _finished = finished;
    [self didChangeValueForKey:@"isFinished"];
}

- (void)completeOperation
{
    self.executing = NO;
    self.finished = YES;
}

- (void)cancel
{
    [self.webView stopLoading];
    [super cancel];
    [self completeOperation];
}



#pragma mark - UIWebViewDelegate methods

- (void)webViewDidFinishLoad:(UIWebView *)webView
{    
    NSString *episodeVideoURLString = [webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('playerelement').getAttribute('data-media')"];
    NSURL *episodeVideoURL = [NSURL URLWithString:episodeVideoURLString];
    self.videoURL = episodeVideoURL;

    if ([self.delegate respondsToSelector:@selector(webViewOperationDidFinish:)]) {
        [self.delegate webViewOperationDidFinish:self];
    }

    [self completeOperation];
}

@end
Cameron Lowell Palmer
  • 21,528
  • 7
  • 125
  • 126
0

Its going to call the delegate method in the same operation queue as main is running in. And NSOperation queues are serial by default. Your while loop is just spinning forever (because the operation is never cancelled) and the call to your delegate method is sitting in the queue behind it never able to run.

Get rid of the while loop entirely and let the operation finish. Then when the delegate method is called, if it's cancelled discard the result by returning.

atomkirk
  • 3,701
  • 27
  • 30
  • BTW, `NSOperationQueue` queues are concurrent by default. If you want it to be serial, you'd have to explicitly set `maxConcurrentOperationCount` to `1` if you want it to be serial. – Rob Sep 16 '14 at 00:52