Search code examples
objective-ccocoaadbnstasknspipe

Run adb commands with NSTask


I'm building a simple GUI to run ADB commands in Cocoa. I have found a few different articles saying how to run shell commands using NSTask, but nothing specific to ADB, and I'm having trouble understanding.

I can run simple ADB commands, e.g.
- adb devices
- adb reboot

Function

NSString *adbPath = @"~/Android/sdk/platform-tools/adb";
NSString* runADBCommand(NSString *cmd)
{
    NSTask *adbDevices = [[NSTask alloc] init];
    [adbDevices setLaunchPath:adbPath];

    adbDevices.arguments = @[cmd];

    NSPipe *pipe;
    pipe = [NSPipe pipe];
    [adbDevices setStandardOutput:pipe];

    NSFileHandle *file;
    file = [pipe fileHandleForReading];

    [adbDevices launch];

    NSData *data;
    data = [file readDataToEndOfFile];

    NSString *adbComOutput;
    adbComOutput = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    return adbComOutput;
}

Call

- (void)refreshDevices:(id)sender
{
    adbOutput.stringValue = runADBCommand(@"devices");
}

The above works fine, but when I pass a more complex argument:

- (void) getVersion:(id)sender
{
    runADBCommand(@"shell cat /system/build.prop | grep incremental");
}

I just get the console output as if I just entered adb in Terminal. How can I package the command and arguments of an NSTask to run ADB commands?


Solution

  • You should set the arguments use the method -[setArguments:] , like this example NSTask shell