Create a "get files Window"which allows to import files

Hello,

I am currently learnign OS development with Swift, I am new to OS development and the applicaiton I am building needs to allow the user to import a file or multiple files from the computer, and once they press "Open Files" a window should open to allow them to look for files, once found added to the app and they should display as icons just like you would expect. These will be mainly text files, .text, .java, .pdf, .c, etc. whats the best way to go about this?


PS: Notice this would not be a file reader/viewer, its more like the app will open the user selected files and save their paths which I will later use for some other functionality.

Accepted Answer

The class you need to use is called NSOpenPanel. This class is a subclass of NSSavePanel (thus, it inherits all methods and properties from that class). Click the API reference links above for all methods and properties of the open panel.


Here is some pseudocode to get you started:


  1. Create a new NSOpenPanel instance.
  2. Set properties (allowedFileTypes, allowsMultipleSelection, showsHiddenFiles, etc.)
  3. Present the panel in a window with beginSheetModal(for:completionHandler:) or by itself with begin(completionHandler:).
  4. Inside the handler, check if the result is equal to NSFileHandlingPanelOKButton.
  5. Retrieve the file URLs with the urls property.


Feel free to ask if you need any additional help! 🙂

How would I go about creating a space where to show the files icons once they have been selected? As of now I was constructing that area as an image view with a white picture as background, is that the correct container to show the files' icons after selecting them?

I recommend using an NSCollectionView instead. Here is an great Swift tutorial (see raywenderlich.com/145978/nscollectionview-tutorial) that shows how to use NSCollectionView. You can then use the URLs from the NSOpenPanel to populate the NSCollectionView. Also, you can use NSURL's getResourceValue(_:forKey:) method with the key effectiveIconKey to get the file's icon.

I am gonna go ahead and give this a try, thank you for all the help!

Create a "get files Window"which allows to import files
 
 
Q