【问题标题】:How can I get the file type description of any file using Objective-C?如何使用 Objective-C 获取任何文件的文件类型描述?
【发布时间】:2020-06-25 17:12:20
【问题描述】:

我希望能够在我的 mac 上获取任何文件的文件类型(或文件类型)。这可以是一个包,一个带或不带扩展名的文件。使用 UTType 的方法有很多,但依赖于知道路径扩展,这不是我想要的。

如何获取在 Finder 信息中显示的文件的确切文件类型描述字符串,但以编程方式使用 Objective-C?

示例:

"/bin/echo" ==> "Unix 可执行文件"

提前致谢。

【问题讨论】:

    标签: objective-c macos file-type finder uti


    【解决方案1】:

    您可以使用-[NSURL resourceValuesForKeys:error:] 请求文件的localized type description

    #import <Foundation/Foundation.h>
    
    int main(int argc, char *argv[]) {
        @autoreleasepool {
            NSURL *url = [NSURL fileURLWithPath:@"/bin/echo"];
            
            NSError *error = nil;
            NSDictionary<NSURLResourceKey, id> *values = [url resourceValuesForKeys:@[NSURLLocalizedTypeDescriptionKey] error:&error];
            
            NSString *description = values[NSURLLocalizedTypeDescriptionKey];
            if (!description) {
                NSLog(@"Failed to get description: %@", error);
            } else {
                NSLog(@"%@", description);
            }
        }
    }
    

    在我的系统上,这会产生与您在 Finder 中看到的相同的“Unix 可执行文件”值。


    在斯威夫特中:

    import Foundation
    
    let url = URL(fileURLWithPath: "/bin/echo")
    let values = try url.resourceValues(forKeys: [.localizedTypeDescriptionKey])
    print(values.localizedTypeDescription) // Optional("Unix executable")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-24
      • 2019-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多