How do you get the details of the currently selected file/folder in a Swift app on macOS?

169 Views Asked by At

I am working on a Swift app for Mac Desktop. My application depends on what file or folder the user has selected in the Finder window. But I don't see any events in FileSystem API or NSWorkspace Shared API to get these details.

Flow of App

  • My application is running in the background
  • User opens Finder and selects any file or folder
  • My app will show the file name or folder name

Please advise or guide in a direction.

I have looked at File System Events, fswatcher, and NSShared Workspace related APIs so far.

1

There are 1 best solutions below

0
marc-medley On

… currently selected file/folder in a Swift app on macOS?

Since FileManager and NSWorkspace have not provided for the current macOS Finder selection, I created (and have been using for several years) a package which wraps some AppleScript with a Swift API via the Apple Open Scripting Architecture (OSA).

Example Use:

import OSAxFinderLib

internal let osaxFinder = OSAxFinder()

let extensions = ["jpg", "png"]
let imageUrls = osaxFinder.selectedFileUrls(extensions: extensions)
for url in imageUrls {
  // …
}

Implemented Scripts:

on finderFrontWindow()
    tell application "Finder"
        set theWin to window 1
        set thePath to (POSIX path of (target of theWin as alias))
    end tell
    return thePath
end finderFrontWindow
on finderSelection()
    tell application "Finder"
        set these_items to the selection as alias list
    end tell
    
    set posixList to {}
    repeat with i from 1 to the count of these_items
        set this_item to (item i of these_items) as alias
        
        -- --- log file information --- 
        -- set this_info to info for this_item
        -- log this_info
        
        -- file list
        set posixForm to (POSIX path of this_item)
        set end of posixList to (posixForm & "\n")
    end repeat
    return posixList as string
end finderSelection

Details:

See GitHub repository: OSAxFinderLib