2

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.

3
  • Do have to 'POST' any data? Commented Apr 18, 2017 at 1:09
  • Nope, all the data are requested as a raw content and will be showing up in the CLI @mat Commented Apr 18, 2017 at 1:10
  • 1
    I question the use of curl here. You'll probably have an easier time with NSURLRequest Commented Apr 18, 2017 at 2:25

2 Answers 2

1
#!/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")
Sign up to request clarification or add additional context in comments.

3 Comments

Hey Adam, thanks for your reply it really helps with the example curl https://api.github.com/zen. However, I'm trying to run another command like: curl -H 'Authorization: token USERTOKEN’ -H 'Accept: application/vnd.github.v3.raw' https://api.github.com/repos/USERNAME/REPO/contents/PATH by inserting double quotations and commas between each flag but I failed to done that. Please help me with that. I also would be so appreciative if you explained more on how the func above is working. Thanks
The method takes as many arguments as you pass. run("curl", "param1", "param2", "paramn"). See [variadic parameters](swift variadic parameters).
The function creates a Process to run the command you pass to it.
0
+50

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

6 Comments

Thanks Oscar for the help. In the runTask func, what should I pass to the launchPath? And regarding the URLSession, if I have a command with many flags, how should I done that? Example: curl -H 'Authorization: token USERTOKEN’ -H 'Accept: application/vnd.github.v3.raw' https://api.github.com/repos/USERNAME/REPO/contents/PATH @Oskar
Actually I'm not really sure what to pass to the url in var request = MutableURLRequest(URL:url), here what I did in main.swift: gist.github.com/MEnnabah/18ecf3fbd95ecee1466d08dab896fcc4 but it's not working.
And where to pass the URL in the first method? @Oskar
I've updated my answer to use the custom request with headers. It should be ready to use except you need to provide a valid USERTOKEN.
I'm really not sure if this ran with you because I'm trying to run it with working data but nothing prints to the console. Even with a URL without headers it's not working!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.