2013-04-15 18 views
0

我正在構建一個監視某些東西的可可應用程序,並且我計劃爲用戶提供一些掛鉤。所以我想讓用戶把一個帶有指定名字(比如說after_event)的腳本(Bash,Ruby,Python)命名爲應用程序支持目錄,並且在我的代碼中的特定事件之後執行腳本。理想情況下,我可以將一些變量傳遞給腳本,以便腳本知道發生了什麼。Mac OS X:使用應用程序中的掛鉤執行腳本

對此的任何想法?

所以問題一是:如何獲得應用程序支持「SDK方式」的路徑?問題二是:如何使用像THAT_APPEND =「foo」這樣的變量來執行腳本?

感謝, 菲利普

+0

好的問題很簡單:http://www.cocoawithlove.com/2010/05/finding-or-creating-application-support.html – plaetzchen

回答

0

查找NSTask documentation。有一個你可以操作的環境成員。以-name = value的形式添加命令行參數也應該是微不足道的。

1

由於共享關愛這裏是執行腳本的方法:我更新的代碼,以便更爲通用:

-(void) runScript:(NSString*)scriptName withVariables:(NSDictionary *)variables 
{ 
NSString *appSupportPath = [NSFileManager defaultManager] applicationSupportDirectory]; 

     NSArray *arguments; 
     NSString* newpath = [NSString stringWithFormat:@"%@/%@",appSupportPath, scriptName]; 
     if ([[NSFileManager defaultManager]fileExistsAtPath:newpath]){ 
      NSTask *task = [[NSTask alloc] init]; 
      [task setLaunchPath: newpath]; 

      NSLog(@"Executing hook: %@",newpath); 
      arguments = [NSArray arrayWithObjects:newpath, nil]; 
      [task setArguments: arguments]; 

      [task setEnvironment:variables]; 

      NSPipe *pipe; 
      pipe = [NSPipe pipe]; 
      [task setStandardOutput: pipe]; 

      NSFileHandle *file; 
      file = [pipe fileHandleForReading]; 

      [task launch]; 

      NSData *data; 
      data = [file readDataToEndOfFile]; 

      NSString *string; 
      string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]; 
      NSLog (@"script returned:\n%@", string); 
     } 

} 

} 

更新。現在NSTask會告訴內核直接執行這個腳本,這樣你的用戶就不能在線使用Bash腳本,而且還可以使用python,perl,php。她需要使用的唯一東西是該文件中的Shebang

可以找到NSFileManager類別here

相關問題