LoginSignup
0
1

More than 3 years have passed since last update.

アプリからFinderを使ってファイル、またはディレクトリのパスを取得する

Posted at

注意

超雑ですごめんなさい。

対象

Flutterを使ってmacosようのアプリを作りたい人

概要

Flutterを使い、macos向けソフトウェアを開発する際、Finderを使って選択したファイルのパスを取得したい。で、これをどうやるか。
(イメージとしてはvscodeのメニューバーのファイルから「開く」を押した時のような感じ)

結論

Flutterのpluginを作ってswiftのコードを呼び出す

let dialog = NSOpenPanel();
dialog.showsResizeIndicator    = true;
dialog.showsHiddenFiles        = false;
dialog.allowsMultipleSelection = true;
dialog.canChooseDirectories = true;

let launcherLogPathWithTilde = rootPath as NSString
let expandedLauncherLogPath = launcherLogPathWithTilde.expandingTildeInPath
dialog.directoryURL = NSURL.fileURL(withPath: expandedLauncherLogPath, isDirectory: true)

if (dialog.runModal() ==  NSApplication.ModalResponse.OK) {
    let result = dialog.url
    if (result != nil) {
      let path: String = result!.path
          return path
    } else {
      // canncelled
      return nil
    }
} else {
   return nil
}

(動けばいいので適当)

本文

ファイルのみ、ディレクトリのみを選択する場合は、公式のプラグインを使用すればよい
こちらを使えば、Finderが開き、ファイルのみ、ディレクトリのみのパスを取得できる。
なお、選択していない方は開けない。
ファイルのみ -> ディレクトリを選択できない。
逆も

今回は、vscodeの「開く」を想像していただきたく、ファイルでもディレクトリでも選べるような(Finderで開くボタンを押せる)ものを作りたい。

> flutter create -t plugin --platforms=linux,macos,windows NAME
これでデスクトップ向けプラグインのテンプレートが作れる。
example/にはアプリから呼び出す例が記述されてる。
lib/にはdart-swift間のクッションコードがある。
macOS/にはswiftのコードと、podspec(?)がある <- ここのFILE.swiftをいじる
linux/にはヘッダーファイルがある <- linuxで何かしたい時はこっち

注意

アプリを動かす際、アプリ側のentitlementsにcom.apple.security.files.user-selected.read-writeを追加しておかないと起動できない。

この記事で登場するソースコード

0
1
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
1