Skip to content

Instantly share code, notes, and snippets.

@ochilab
Created April 25, 2024 05:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ochilab/040cedbc905f2dddd3d9265490ff8e9d to your computer and use it in GitHub Desktop.
Save ochilab/040cedbc905f2dddd3d9265490ff8e9d to your computer and use it in GitHub Desktop.
MacOS上でFlutterアプリからシェルコマンドを実行するためのMethodChannelを実装する
import Cocoa
import FlutterMacOS
@NSApplicationMain
class AppDelegate: FlutterAppDelegate {
override func applicationDidFinishLaunching(_ notification: Notification) {
let controller : FlutterViewController = mainFlutterWindow?.contentViewController as! FlutterViewController
let shellChannel = FlutterMethodChannel(name: "shell_executor",
binaryMessenger: controller.engine.binaryMessenger)
shellChannel.setMethodCallHandler({
(call: FlutterMethodCall, result: @escaping FlutterResult) -> Void in
if call.method == "executeCommand" {
self.executeShellCommand(command: call.arguments as! String, result: result)
} else {
result(FlutterMethodNotImplemented)
}
})
super.applicationDidFinishLaunching(notification)
}
private func executeShellCommand(command: String, result: FlutterResult) {
let process = Process()
process.launchPath = "/bin/bash"
process.arguments = ["-c", command]
let pipe = Pipe()
process.standardOutput = pipe
process.launch()
process.waitUntilExit()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: .utf8)
result(output)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment