简体   繁体   中英

See NSTask output Cocoa

How could I make an if statement that's like:

if(the output of a nstask is equal to a specific string){
   //do stuff over here
}

I'm running a NSTask and it put's out the data that's coming from it in the NSLog, but how could I not show it there but store it as a NSString or something like that

This is what my task looks like

NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:@"/usr/bin/csrutil"];
[task setArguments:@[ @"status" ]];
[task launch];

Any help is greatly appreciated :)

You need a pipe and a file handle to read the result.

Write a method

- (NSString *)runShellScript:(NSString *)cmd withArguments:(NSArray *)args
{
    NSTask *task = [[NSTask alloc] init];
    [task setLaunchPath:cmd];
    [task setArguments:args];

    NSPipe *pipe = [NSPipe pipe];
    [task setStandardOutput: pipe];
    NSFileHandle *file = [pipe fileHandleForReading];

    [task launch];

    NSData *data = [file readDataToEndOfFile];
    return [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
}

and call it

NSString *result = [self runShellScript:@"/usr/bin/csrutil" withArguments:@[ @"status" ]];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM