Created
April 25, 2024 05:13
-
-
Save ochilab/040cedbc905f2dddd3d9265490ff8e9d to your computer and use it in GitHub Desktop.
MacOS上でFlutterアプリからシェルコマンドを実行するためのMethodChannelを実装する
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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