我可以从Cocoa应用程序中的已知本地目录运行可执行文件,如下所示:
// Run the server.
NSTask *task = [[NSTask alloc] init];
NSPipe *pipe = [NSPipe pipe];
NSString* scriptPath = @"/Users/example/Server/runServerExecutable.sh";
[task setLaunchPath: @"/bin/sh"];
[task setArguments: [NSArray arrayWithObjects: scriptPath, nil]];
[task setStandardOutput: pipe];
[task launch];
有人可以帮我解决这些问题吗?
scriptPath
以编程方式运行脚本?非常感谢!
答案 0 :(得分:0)
将脚本/文本文件拖放到xcode项目中 - > Project Navigator,以便它将添加到您的项目中。建立项目。打开Bundle,您将能够在Resources目录中看到添加的文件。
现在,下面给出的代码将帮助您从资源中获取文件。为了举例,我添加了一个名为" OpenSafari.sh"的脚本。
NSTask *temp = [[NSTask alloc] init];
[temp setLaunchPath:@"/bin/sh"];
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"OpenSafari" ofType:@"sh"];
NSArray *tempargs = [NSArray arrayWithObjects:filePath,nil];
[temp setArguments:tempargs];
NSPipe *temppipe = [NSPipe pipe];
[temp setStandardOutput:temppipe];
NSPipe *errorPipe = [NSPipe pipe];
[temp setStandardError:errorPipe];
[temp launch];
NSData *data = [[temppipe fileHandleForReading] readDataToEndOfFile];
NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSData *dataErr = [[errorPipe fileHandleForReading] readDataToEndOfFile];
NSString *resultErr = [[NSString alloc] initWithData:dataErr encoding:NSUTF8StringEncoding];
希望这有帮助!