Re: Reading data from an NSTask [SOLVED]
Re: Reading data from an NSTask [SOLVED]
- Subject: Re: Reading data from an NSTask [SOLVED]
- From: Ken Tozier <email@hidden>
- Date: Mon, 4 Jul 2005 19:11:08 -0400
For future NSTask seekers, here's a little category, anyone is free
to use, that encapsulates all the manual junk you have to do to run a
task synchronously
@interface NSTask (ConvenienceMethods)
+ (NSData *) runTaskWithExecutable:(NSString *) inPath
parameters:(NSArray *) inParams;
@end
@implementation NSTask (ConvenienceMethods)
+ (NSData *) runTaskWithExecutable:(NSString *) inPath
parameters:(NSArray *) inParams
{
NSPipe *pipe = [NSPipe pipe];
NSFileHandle *fileHandle = [pipe fileHandleForReading];
NSData *data = nil;
NSMutableData *taskData = [NSMutableData data];
NSTask *testTask = [[NSTask alloc] init];
[testTask setArguments: inParams];
[testTask setLaunchPath: inPath];
[testTask setStandardOutput: pipe];
[testTask setStandardError: pipe];
[testTask launch];
// loop until there's no more data
while ((data = [fileHandle availableData]) && [data length])
{
[taskData appendData: data];
}
[testTask waitUntilExit];
if ([testTask terminationStatus] == 0)
return taskData;
else
NSLog(@"task failed with error = %@", [[NSString alloc]
initWithData: taskData encoding: NSUnicodeStringEncoding]);
return nil;
}
@end
Usage examples:
// Read a nib file on the desktop:
NSData *nibData = [NSTask runTaskWithExecutable: @"/usr/bin/
nibtool"
parameters:
[NSArray arrayWithObjects: @"-a", @"/Users/someuser/Desktop/
somenib.nib"];
Terminal equivalent: > nibtool -a "/Users/someuser/Desktop/somenib.nib"
// List the contents of the current user's home directory in long form
NSData *listDir = [NSTask runTaskWithExecutable: @"/bin/ls"
parameters:
[NSArray arrayWithObjects: @"-l", @"/Users/someuser/", nil]];
Terminal equivalent: > ls -l "/Users/someuser/"
Enjoy
Ken
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden