Skip to content

Commit

Permalink
Added example
Browse files Browse the repository at this point in the history
  • Loading branch information
philippm committed Feb 4, 2011
1 parent db71bac commit 7f18ff7
Showing 1 changed file with 61 additions and 0 deletions.
61 changes: 61 additions & 0 deletions README.md
Expand Up @@ -5,6 +5,67 @@ BETaskHelper helps you run NSTask interactively. Specifically you can:
- receive output of the task line-by-line
- send strings such as passwords to the task

## Example

This example uses the `openssl` command to encrypt a file.

In the header file implement the `BETaskHelperDelegate` protocol:

#import "BETaskHelper.h"

@interface FileEncrypter : NSObject <BETaskHelperDelegate> {
BETaskHelper *taskHelper;
}

// Sets up and runs the find task (you can call the method anything you like)
-(void) run;

@end

Note that we keep the task helper as an instance variable because the task runs asynchronously.

In the implementation file use the `BETaskHelper` delegate methods to capture the output of the `openssl` command and send the password when requested:

#import "FileEncrypter.h"

@implementation FileEncrypter

-(void) run {
// Setup task
NSTask *task = [[[NSTask alloc] init] autorelease]; // BETaskHelper will retain it for us
[task setLaunchPath:@"/usr/bin/openssl"];
NSString *inputPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Report.txt"];
NSString *outputPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Report.enc"];
[task setArguments:[NSArray arrayWithObjects:@"enc", @"-aes-256-cbc", @"-salt", @"-in", inputPath, @"-out", outputPath, nil]];
// Hook up task with helper
taskHelper = [[BETaskHelper alloc] initWithDelegate:self forTask:task];
// Launch task -- must happen via task helper!
[taskHelper launchTask];
}

#pragma mark BETaskHelper delegate methods

-(void) task:(NSTask *)task hasOutputAvailable:(NSString *)outputLine {
// Log all output
NSLog(@"%@", outputLine);

// Send password if requested (will be called twice for verification)
if ([outputLine rangeOfString:@" password:"].location != NSNotFound) {
// Most commands require newline character to signal end of input
[taskHelper sendInput:@"YouWillNeverGuess\n"];
}
}

-(void) task:(NSTask *)task hasCompletedWithStatus:(int) status {
NSString *message = (status == 0) ? @"Success!" : @"Failed!";
NSLog(@"%@", message);
}

@end

## License

Copyright (c) 2007, Incredible Bee Ltd. All rights reserved.
Expand Down

0 comments on commit 7f18ff7

Please sign in to comment.