0

I can run an executable from a known local directory within a Cocoa app like this:

// 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];

Could anyone help me on these questions?

  • Where should I include the executable/script/text files in the app bundle?
  • How to modify scriptPath to run the script programmatically?

Thanks a lot!

4

1 に答える 1

0

スクリプト/テキスト ファイルを xcode プロジェクト -> Project Navigator にドラッグ アンド ドロップして、プロジェクトに追加します。プロジェクトをビルドします。バンドルを開くと、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];

お役に立てれば!

于 2015-01-02T09:00:49.313 に答える