NSMetadataQueryDidUpdateNotification, can't get this to work. Code Snippet included

253 Views Asked by At

I can't get the NSMetadataQueryDidUpdateNotification to work. Been stuck at it for days. Is there something abnormal in the code below.

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0ul), ^{


    NSString* filePattern = [NSString stringWithFormat:@"*.%@", @"*"];

        NSMetadataQuery *aQuery = [[NSMetadataQuery alloc] init];
        aQuery.predicate = [NSPredicate predicateWithFormat: @"%K LIKE %@", NSMetadataItemFSNameKey, filePattern];

        [aQuery setSearchScopes:@[NSMetadataQueryUbiquitousDataScope]];
        [aQuery setValueListAttributes:@[NSMetadataUbiquitousItemPercentDownloadedKey, NSURLUbiquitousItemDownloadingStatusKey,NSURLUbiquitousItemIsDownloadingKey,NSURLUbiquitousItemDownloadRequestedKey]];

        _query = aQuery;

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                                 selector:@selector(liveUpdate:)
                                                                     name:NSMetadataQueryDidUpdateNotification
                                                                   object:aQuery];

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initalGatherComplete:)                                                                                          name:NSMetadataQueryDidFinishGatheringNotification object:aQuery];

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(gatherProgress:)                                                                                          name:NSMetadataQueryGatheringProgressNotification object:aQuery];

        [aQuery enableUpdates];

         dispatch_async(dispatch_get_main_queue(), ^{

        [aQuery startQuery];


        });


        });
2

There are 2 best solutions below

1
On

Hope this helps you

Try replace with this code about notification And metadata query should be started on main queue, you did it right :)

    [[NSNotificationCenter defaultCenter] addObserver:self  
selector:@selector(liveUpdate:) 
name:NSMetadataQueryDidUpdateNotification 
object:aQuery];

    [[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(initalGatherComplete:)
name:NSMetadataQueryDidFinishGatheringNotification 
object:aQuery];

And this is example for processing gathering notification

- (void)initialGatherComplete:(NSNotification*)notification
{
      //process here.
}
0
On

The solution is to strong reference the notification block as such

    _notifqueryDidUpdate = [[NSNotificationCenter defaultCenter]addObserverForName:NSMetadataQueryDidUpdateNotification object:aQuery queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {

                                [self liveUpdate:note];

                            }];