-2

I have been working on a command line tool in swift but due to excessive size of the executable(around 10 mb) I need to re-write it in objective-c. Now I am not a fan of objective-c, thanks to it's lengthy syntax. So I have this function which I use to call my shell script and return the output. Can some please convert this into objective-c, I am having a hard time.

func shell(_ args: String) -> String {
    var outstr = ""
    let task = Process()
    task.launchPath = "/bin/sh"
    task.arguments = ["-c", args]
    let pipe = Pipe()
    task.standardOutput = pipe
    task.launch()
    let data = pipe.fileHandleForReading.readDataToEndOfFile()
    if let output = NSString(data: data, encoding: String.Encoding.utf8.rawValue) {
        outstr = output as String
    }
    task.waitUntilExit()
    return outstr
}

then I call this method in swift something like

let shellOutput = shell("sh \(scriptPath) \(arg1) \(arg2)")

before you mark it duplicate or post answers, I really need the shell script output in some variable.

5
  • 7
    I think you'll find you get better answers by including the ObjC code you have tried to write, and where you are getting stuck. What part are you having a hard time with? Commented Jan 7, 2019 at 20:12
  • I'm going to question the premise here. Why is the 10 MB executable size an issue? What size optimizations have you tried making? What makes you think the Objective C variant would be smaller? Commented Jan 7, 2019 at 20:14
  • stackoverflow.com/a/696942/4311935 Commented Jan 7, 2019 at 20:15
  • @Alexander the size bloat is because of swift not supporting ABI. In objective-c, literally it is of kbs. reason being I think the executable contains all of swift binaries while building Commented Jan 7, 2019 at 20:18
  • 1
    Search SO for "[objective-c] nstask pipe.fileHandleForReading readDataToEndOfFile" and you'll find examples. Commented Jan 7, 2019 at 22:37

1 Answer 1

0
NSString *shell(NSString *args)
{
    NSTask *task = [NSTask new];
    task.launchPath = @"/bin/sh";
    task.arguments = @[ @"-c", args ];
    NSPipe *pipe = [NSPipe new];
    task.standardOutput = pipe;
    [task launch];
    NSData *data = [[pipe fileHandleForReading] readDataToEndOfFile];
    NSString *output = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    [task waitUntilExit];
    return output;
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.