首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NSMetadataQuery不返回任何数据

NSMetadataQuery不返回任何数据
EN

Stack Overflow用户
提问于 2016-08-01 19:47:41
回答 1查看 901关注 0票数 2

我试着在我的Mac上列出我制作的一个应用程序的所有文件。我使用NSMetadataQuery,但它不工作。

代码如下:

代码语言:javascript
复制
import Cocoa

class ViewController: NSViewController
{

let metadataQuery = NSMetadataQuery()

@IBOutlet weak var searchTextField: NSTextField!

@IBOutlet weak var labelML: NSTextField!

@IBAction func searchClick(sender: AnyObject)
{
    labelML.stringValue = "Hello \(searchTextField.stringValue)!"
    startQuery()
    handleMetadataQueryFinished(metadataQuery)
}

override func viewDidLoad()
{
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}


func startQuery()
{
    print("Starting the query now...")

    metadataQuery.searchScopes = [NSMetadataQueryUbiquitousDataScope]
    let predicate = NSPredicate(format: "%K ==[cd] '*'", NSMetadataItemFSNameKey)

    metadataQuery.predicate = predicate
    if metadataQuery.startQuery(){
        print("Successfully started the query.")
    } else {
        print("Failed to start the query.")
    }

}

func handleMetadataQueryFinished(sender: NSMetadataQuery)
{

    print("Search finished");
    metadataQuery.disableUpdates()
    metadataQuery.stopQuery()
    print("Number of results \(metadataQuery.resultCount)")

    for item in metadataQuery.results as! [NSMetadataItem]
    {

        let itemName = item.valueForAttribute(NSMetadataItemFSNameKey)
            as! String

        let itemUrl = item.valueForAttribute(NSMetadataItemURLKey)
            as! NSURL

        let itemSize = item.valueForAttribute(NSMetadataItemFSSizeKey)
            as! Int
        print("Item name = \(itemName)")
        print("Item url = \(itemUrl)")
        print("Item size = \(itemSize)")

    }

    }

}

正如您所看到的,我输出了metaQuery的结果数,结果是0。

我试着改变一些东西,比如用NSMetadataQueryIndexedLocalComputerScope代替NSMetadataQueryUbiquitousDataScope,或者改变谓词的格式,但是这两种方法都不起作用。

知道为什么吗?

EN

回答 1

Stack Overflow用户

发布于 2016-08-11 17:27:49

您应该为NSMetadataQueryDidFinishGatheringNotification注册一个观察者,并等待它被调用。搜索需要一小段时间。并启动查询返回true

下面是我的代码中一些Objective-C风格的示例:

代码语言:javascript
复制
#import "CloudUtils.h"

@interface CloudUtils ()
@property(nonatomic, strong) NSMetadataQuery *query;
@end

@implementation CloudUtils

static CloudUtils *singleton;

+ (CloudUtils *) sharedInstance
{
    if (singleton == nil) {
        singleton = [[CloudUtils alloc] init];
    }
    return singleton;
}

+ (void) updateCloudDrive
{
    NSLog(@"in updateCloudDrive");

    CloudUtils *utils = [CloudUtils sharedInstance];

    // Wichtig: Das Query muss STRONG gebunden sein... sonst ist das zu früh wieder weg!
    utils.query              = [[NSMetadataQuery alloc] init];
    utils.query.searchScopes = [NSArray arrayWithObjects:NSMetadataQueryUbiquitousDocumentsScope, NSMetadataQueryUbiquitousDataScope,nil];
    utils.query.predicate    = [NSPredicate predicateWithFormat:@"%K like[cd] %@", NSMetadataItemFSNameKey, @"*"];

    [[NSNotificationCenter defaultCenter] addObserver:utils
                                             selector:@selector(queryDidFinishGathering:)
                                                 name:NSMetadataQueryDidFinishGatheringNotification
                                               object:utils.query];

    [[NSNotificationCenter defaultCenter] addObserver:utils
                                             selector:@selector(queryDidUpdate:)
                                                 name:NSMetadataQueryDidUpdateNotification
                                               object:utils.query];

    dispatch_async(dispatch_get_main_queue(), ^{
        // Das scheitert, falls schon ein solches Query läuft... was aber nicht schlimm ist.
        [utils.query startQuery];
    });
}

// Diese Methode kommt ins Spiel, wenn es zu viele Ergebnisse auf einmal sind...
// Dann werden einige davon schon gemeldet, bevor das Query ganz fertig ist...
- (void) queryDidUpdate: (NSNotification *) notification
{
    NSLog(@"in queryDidUpdate:");

    NSMetadataQuery *query = [notification object];
    [query disableUpdates];
    NSError *error = nil;
    for (NSMetadataItem *item in [query results]) {
        NSURL *url = [item valueForAttribute:NSMetadataItemURLKey];
        NSLog(@"starting download of %@", url);
        [[NSFileManager defaultManager] startDownloadingUbiquitousItemAtURL:url error:&error];
    }
    [query enableUpdates];
}

- (void) queryDidFinishGathering: (NSNotification *) notification
{
    NSLog(@"in queryDidFinishGathering:");

    NSMetadataQuery *query = [notification object];
    [query disableUpdates];
    [query stopQuery];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NSMetadataQueryDidFinishGatheringNotification object:query];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NSMetadataQueryDidUpdateNotification          object:query];

    NSError *error = nil;
    for (NSMetadataItem *item in [query results]) {
        NSURL *url = [item valueForAttribute:NSMetadataItemURLKey];
        NSLog(@"starting download of %@", url);
        [[NSFileManager defaultManager] startDownloadingUbiquitousItemAtURL:url error:&error];
    }
}

@end
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38698067

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档