Search code examples
objective-ccocoaapp-bundle

How to include and call an executable in a Cocoa app?


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!


Solution

  • Drag and drop the script/text files to your xcode project -> Project Navigator, so that it will get added to your project. Build the project. Open the Bundle, you will be able to see the added file in Resources directory.

    Now, the code given below will help you get the file from the resources. For the sake of example, I have added a script by the name "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];
    

    Hope this helps!