Kyle
Kyle

Reputation: 17677

Cocoa icon for file type?

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

NSImage *iconImage = [[NSWorkspace sharedWorkspace] iconForFile: @"myFile.png"];

But if I just wanted to get the icon for a specific file type (example the icon associated with png files, without having a "myFile.png" that already exists), i'm not sure how I can do that.

Any suggestions are appreciated!

Upvotes: 14

Views: 6293

Answers (4)

Ky -
Ky -

Reputation: 32073

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)
    }
}

Upvotes: 0

Ky -
Ky -

Reputation: 32073

Here is the Swift 5 version of Dave DeLong's answer:

icon(forFile:)

Returns an image containing the icon for the specified file.

Declaration

func icon(forFile fullPath: String) -> NSImage

Parameters

fullPath
The full path to the file.

icon(forFileType:)

Returns an image containing the icon for files of the specified type.

Declaration

func icon(forFileType fileType: String) -> NSImage

Parameters

fileType
The file type, which may be either a filename extension, an encoded HFS file type, or a universal type identifier (UTI).

Upvotes: 1

PetrV
PetrV

Reputation: 1368

You can first determine file type (UTI) and then pass it on to get icon:

NSString *fileName = @"lemur.jpg"; // generic path to some file
CFStringRef fileExtension = (__bridge CFStringRef)[fileName pathExtension];
CFStringRef fileUTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileExtension, NULL);

NSImage *image = [[NSWorkspace sharedWorkspace]iconForFileType:(__bridge NSString *)fileUTI];

Upvotes: 4

Dave DeLong
Dave DeLong

Reputation: 243146

Underneath -[NSWorkspace iconForFile:] in the documentation is -[NSWorkspace iconForFileType:]. Have you tried that?

Upvotes: 27

Related Questions