Execute Swift script in terminal

I have created a command line tool, at some point I need to execute a command curl

. I am creating a script that needs to be executed, but I don't know how to do it.

I can create a script and print it, but I cannot execute it.
It looks something like this:curl https://api.github.com/zen

Please ask me if this is not clear. I appreciate your help.

+3


source to share


2 answers


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()

to the end. Here's the whole thing wrapped in a function (startPath will 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, however, you can look at URLSession

and URLRequest

(replacing NSURLRequest

). To create a request for your url and credentials, you 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()

      

+1


source


#!/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")

      



+1


source







All Articles