Created
July 22, 2015 19:21
-
-
Save Seasons7/836d3676884a40c8c98a to your computer and use it in GitHub Desktop.
NSTask Sample for Swift
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 Foundation | |
var str = "Hello, playground" | |
var task:NSTask = NSTask() | |
var pipe:NSPipe = NSPipe() | |
task.launchPath = "/bin/ls" | |
task.arguments = ["-la"] | |
task.standardOutput = pipe | |
task.launch() | |
var handle = pipe.fileHandleForReading | |
var data = handle.readDataToEndOfFile() | |
var result_s = NSString(data: data, encoding: NSUTF8StringEncoding) | |
print(result_s) |
is it possible to run multiple commands?
Updated for Swift 4
//: Playground - noun: a place where people can play
import Cocoa
import Foundation
var task = Process()
var pipe = Pipe()
task.executableURL = URL(fileURLWithPath: "/bin/ls")
task.arguments = ["-la","/Users/"] //multiple options
task.standardOutput = pipe
try task.run()
var handle = pipe.fileHandleForReading
var data = handle.readDataToEndOfFile()
var printing = String (data: data, encoding: String.Encoding.utf8)
print(printing!)
I'm using this method for running app but I got "Message from debugger: Terminated due to signal 9".Any idea?
let path=("\(FileManager.default.currentDirectoryPath)/data/app/setup.pkg")
let buildTask: Process = Process()
//Path for open
buildTask.launchPath = "/usr/bin/open"
buildTask.arguments = [path]
buildTask.launch()
Message from debugger: Terminated due to signal 9
buildTask.launch()
is not up to date anymore. Since High Sierra, Process().lauch()
is deprecated. Use Process().run
instead and catch the error that may be thrown.
See Apple Developer Documentation for launch()
This Tutorial goes a bit more into detail regarding NSTasks.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@ingconti: Do you have any sample how to interact with standardInput? And why Process is Task on Swift 3 for Linux? Thank you.