Cocoa icon for file type?

后端 未结 4 858
轮回少年
轮回少年 2021-02-05 15:39

If I have a file, I can get the icon by doing something such as:

NSImage *iconImage = [[NSWorkspace sharedWorkspace] iconForFile: @\"myFile.png\"];
4条回答
  •  我在风中等你
    2021-02-05 16:32

    Here is the Swift 5 version of PetrV's answer:

    public extension NSWorkspace {
    
        /// Returns an image containing the icon for files of the same type as the file at the specified path.
        ///
        /// - Parameter filePath: The full path to the file.
        /// - Returns: The icon associated with files of the same type as the file at the given path.
        func icon(forFileTypeAtSamplePath filePath: String) -> NSImage? {
            let fileExtension = URL(fileURLWithPath: filePath).pathExtension
            guard
                let unmanagedFileUti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension,
                                                                             fileExtension as CFString, nil),
                let fileUti = unmanagedFileUti.takeRetainedValue() as String?
                else {
                    assertionFailure("Should've gotten a UTI for \(fileExtension)")
                    return nil
            }
    
            return NSWorkspace.shared.icon(forFileType: fileUti)
        }
    }
    

提交回复
热议问题