在 macOS Quicklook 预览中显示实际文件图标

Show actual file icon in macOS Quicklook Preview

我正在为我的应用程序编写一个 QuickLook 扩展,我希望能够显示特定文件的实际图标图像,如 Finder 中所示。我试过为此使用 QLThumbnailGenerator,但它总是 return 纯白色文档图标。

QLThumbnailGenerationRequest *request = [[QLThumbnailGenerationRequest alloc] initWithFileAtURL:url size:size scale:scale representationTypes:QLThumbnailGenerationRequestRepresentationTypeIcon];

QLThumbnailGenerator *generator = [QLThumbnailGenerator sharedGenerator];

__unsafe_unretained PreviewViewController *weakSelf = self;

[generator generateBestRepresentationForRequest:request completionHandler:^(QLThumbnailRepresentation *thumbnail, NSError *error) {
    dispatch_async(dispatch_get_main_queue(), ^{
        if (thumbnail == nil || error) {
            NSLog(@"Failed to generate thumbnail! %@", error);
            // Handle the error case gracefully
        } else {
            // Display the thumbnail that you created
            NSLog(@"Generated thumbnail!");
            weakSelf.imageView.image = thumbnail.NSImage;
        }
    });
}];

原码here.

这更像是一种变通方法,但改用 iconForFile 方法,即 _imageView.image = [[NSWorkspace sharedWorkspace] iconForFile:url.path] 可以满足我的要求。