いくつかのコマンドラインスクリプトを実行するためにcocoaアプリでコードを実行するときに問題に直面しています
この機能は、コマンドラインツールを使用するとスムーズに実行されますが、一部のオンオフUIを備えたフルココアアプリを使用すると、まったく機能しません
スクリプトでhttp&httpsプロキシをオン/オフにする必要があります
これが私の機能です:
private func runTask(_ cmd: String) {
// Create a Task instance
let task = Process()
// Set the task parameters
task.launchPath = "/bin/sh"
task.arguments = ["-c", String(format:"%@", cmd)]
// Create a Pipe and make the task
// put all the output there
let pipe = Pipe()
task.standardOutput = pipe
// Launch the task
task.launch()
// Get the data
let data = pipe.fileHandleForReading.readDataToEndOfFile()
guard let output = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return }
print(output)
}
そして、これが私の完全なViewControllerクラスです。
import Cocoa
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func onButtonTapped(_ sender: NSButton) {
print("onButtonTapped")
let selected: Switch = .on
let listOfNetworkCommands: String = [
#"networksetup -setwebproxystate "Wi-fi" \#(selected)"#, // switch http proxy
#"networksetup -setsecurewebproxystate "Wi-fi" \#(selected)"#, // switch https proxy
#"networksetup -setpassiveftp "Wi-fi" \#(selected)"# // switch passive ftp
].joined(separator: " && ")
runTask(listOfNetworkCommands)
}
@IBAction func offButtonTapped(_ sender: NSButton) {
print("onButtonTapped")
let selected: Switch = .off
let listOfNetworkCommands: String = [
#"networksetup -setwebproxystate "Wi-fi" \#(selected)"#, // switch http proxy
#"networksetup -setsecurewebproxystate "Wi-fi" \#(selected)"#, // switch https proxy
#"networksetup -setpassiveftp "Wi-fi" \#(selected)"# // switch passive ftp
].joined(separator: " && ")
runTask(listOfNetworkCommands)
}
enum Switch: String {
case on, off
}
private func runTask(_ cmd: String) {
// Create a Task instance
let task = Process()
// Set the task parameters
task.launchPath = "/bin/sh"
task.arguments = ["-c", String(format:"%@", cmd)]
// Create a Pipe and make the task
// put all the output there
let pipe = Pipe()
task.standardOutput = pipe
// Launch the task
task.launch()
// Get the data
let data = pipe.fileHandleForReading.readDataToEndOfFile()
guard let output = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return }
print(output)
}
}
私の関数がココアアプリでトリガーされない理由は何ですか?
簡単な答えは、Cocoaアプリケーションでアプリサンドボックスを無効にすることで見つかります(プロジェクトアプリのターゲット> [機能]タブ> [アプリサンドボックス]スイッチの下にあります)。サンドボックスの例外によってブロックされていることがわかります。サンドボックスを無効にすると、問題が解決するはずです。
アプリ名またはサンドボックス化されたプロセスでフィルタリングすると、Console.appでもこれを確認できます。サンドボックスが有効になっていると、次のようなエントリが表示される可能性があります。
エラー00:21:57.502273 +0000 sandboxdサンドボックス:sh(17363)deny(1)file-read-data / dev / ttys003
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加