LoginSignup
0
2

More than 1 year has passed since last update.

[macos] 指定ディレクトリ中のファイルURLを一括取得する

Posted at

MacOSアプリをSwiftUIで作ってます。
モバイルエンジニアのEtsuwoです。

ユーザが指定したディレクトリ中のファイルURLを一括取得する方法をご紹介します。
以下の手順で説明します。

  1. ディレクトリ選ぶパネルを開いてユーザに選んでもらう
  2. 選択したディレクトリ中のファイルURLを一括取得

1. ディレクトリ選ぶパネルを開いてユーザに選んでもらう

まず、どのディレクトリの中身を一括取得するかユーザに選んでもらいます。
ユーザにディレクトリを選ばせるwindowを表示するにはNSOpenPanelを使用します。

OpenPanel.swift
final class OpenPanelHandler {

    /// ディレクトリ選択用のパネルを開く
    func openSelectDirectoryPanel() -> URL? {
        let panel = NSOpenPanel.selectDirectoryPanel()
        if panel.runModal() == .OK {
            return panel.url // 正常にディレクトリが指定された場合はディレクトリのURL返す
        }
        return nil // 選択しなかったりした場合はnilを返す
    }
}

extension NSOpenPanel {

    /// パネルの設定を行う
    /// 今回はディレクトリのみ選択できるようカスタマイズ
    static func selectDirectoryPanel() -> NSOpenPanel {
        let openPanel = NSOpenPanel()
        openPanel.canChooseFiles = false // ファイルを選択できるか
        openPanel.canChooseDirectories = true // ディレクトリを選択できるか
        openPanel.allowsMultipleSelection = false // 複数選択できるか
        openPanel.message = "フォルダを選択してください"
        return openPanel
    }
}

以上の実装で、ディレクトリを選択させたい場面でOpenPanelHandler().openSelectDirectoryPanel()としてあげると以下のようなパネルを開くことができます。

スクリーンショット 2022-01-29 15.50.36.png

このパネルでディレクトリ選んでOpenボタン押すとpanel.urlに指定ディレクトリのURLが入ってきます。

2. ディレクトリ中のファイルURLを一括取得する

ディレクトリ内のファイルURLを一括取得するにはFileManagercontentsOfDirectory(atPath:)を使用します。
注意点としては、contentsOfDirectory(atPath:)は当該ディレクトリ中のみの検索になるので、サブディレクトリや親ディレクトリの内容を検索することはできません。子ディレクトリ中の検索も行いたい場合はenumerator(at:includingPropertiesForKeys:options:errorHandler:)を使えば良いようです。
参考: contentsOfDirectory(atPath:)

今回は選択したディレクトリ中のファイルURLが取得できれば良いのでcontentsOfdirectoryでOKです。

OpenPanel.swift
    private func getContentsUrls(from url: URL) -> [URL] {
        var urls: [URL] = []
        do {
            urls = try FileManager.default.contentsOfDirectory(at: url, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
        } catch {
            print(error.localizedDescription)
        }
        return urls
    }

これで先ほどOpenPanelを使って取得したURLをgetContentsUrlsに渡してやればディレクトリ中のファイルを配列で返してくれます。

以上です。

参考文献

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2