Ennabah
Ennabah

Reputation: 2533

Execute a Swift script in terminal

I have built a command line tool, at some point, I need to execute a curl command. I'm creating the script that should be executed, but I don't know how.

I'm able to create the script and printing it out, but I'm not being able to execute it.
It looks something like: curl https://api.github.com/zen

Please ask me anything if it's not clear. I appreciate your help.

Upvotes: 2

Views: 2443

Answers (2)

Oskar
Oskar

Reputation: 3702

You can run a Terminal command from Swift using NSTask (now called Process in Swift 3): If you need output, add let output = handle.readDataToEndOfFile() at the end. Here's the whole thing wrapped in a function (the launchPath would be /usr/bin/curl):

func runTask(launchPath: String, flags: [String]) -> String {
    let task = Process()
    let pipe = Pipe()
    task.launchPath = launchPath
    task.arguments = flags
    task.standardOutput = pipe
    let handle = pipe.fileHandleForReading
    task.launch()
    return String(data: handle.readDataToEndOfFile(), encoding: .utf8) ?? ""
}

In your case though, you might want to have a look at URLSession and URLRequest (superseding NSURLRequest). To create a request to your URL and credentials, you would simply do:

    var request = URLRequest(url:URL(string: "https://api.github.com/zen")!)
    request.setValue("application/vnd.github.v3.raw", forHTTPHeaderField: "Accept")
    request.setValue("token USERTOKEN", forHTTPHeaderField: "Authorization")
    let session = URLSession(configuration: .default)
    session.dataTask(with: request, completionHandler: {(data, response, error) in
        guard let data = data, error == nil else {
            print("Error: \(error.debugDescription)")
            return
        }
        guard let output = String(data: data, encoding: .utf8) as String? else {
            print("Unable to format output data")
            return
        }
        print(output)
    }).resume()

Upvotes: 0

Adam Eri
Adam Eri

Reputation: 965

#!/usr/bin/env swift

import Foundation

func run(_ args: String...) -> Int32 {
    let task = Process()
    task.launchPath = "/usr/bin/env"
    task.arguments = args
    task.launch()
    task.waitUntilExit()
    return task.terminationStatus
}

run("curl", "https://api.github.com/zen")

Upvotes: 1

Related Questions