-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.

SUMIT NIHALANI
  • 387
  • 1
  • 10
  • 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? – Mattie Jan 07 '19 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? – Alexander Jan 07 '19 at 20:14
  • https://stackoverflow.com/a/696942/4311935 – canister_exister Jan 07 '19 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 – SUMIT NIHALANI Jan 07 '19 at 20:18
  • 1
    Search SO for "[objective-c] nstask pipe.fileHandleForReading readDataToEndOfFile" and you'll find examples. – Willeke Jan 07 '19 at 22:37

1 Answers1

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;
}
Gergely
  • 3,025
  • 2
  • 14
  • 13