【问题标题】:Launch OS X Application Programmatically以编程方式启动 OS X 应用程序
【发布时间】:2015-11-18 17:25:24
【问题描述】:

如何以编程方式打开包含在我正在构建的应用程序中的 OS X 应用程序 (.app)?

【问题讨论】:

  • 您可以使用“open /path/to/file.app”进行系统终端调用
  • 如果我要打开的应用程序包含在当前应用程序的捆绑包中,路径会是什么?
  • 你可以试试NSString *path = [[NSBundle mainBundle] pathForResource:@"myapp.app"]; system([[NSString stringWithFormat:@"open %@", path] UTF8String])

标签: xcode macos osx-yosemite


【解决方案1】:

在 OS X 上执行此操作的首选方法是通过 NSWorkspace 类,它提供了几种启动应用程序的方法。其中之一,launchApplicationAtURL:options:configuration:error: 允许您指定要启动的应用程序的文件 URL。除了没有像system() 和Apple Event 解决方案这样的沙盒问题外,它还为您提供了一种操作应用程序启动方式的简单方法,例如。您可以指定要传递给应用程序的环境变量。

【讨论】:

    【解决方案2】:

    以下代码 sn-p 用于以编程方式启动应用程序:

    NSString *path = [[[NSBundle mainBundle] bundlePath] stringByDeletingLastPathComponent];
    path = [path stringByAppendingString:@"/MyApp.app"]; // App Path
    NSWorkspace *ws=[NSWorkspace sharedWorkspace];
    NSURL* url = [NSURL fileURLWithPath:path isDirectory:NO];
    [ws launchApplicationAtURL:url
                               options:NSWorkspaceLaunchWithoutActivation
                         configuration:nil
                                 error:nil];
    

    【讨论】:

      【解决方案3】:

      您可以使用 Apple 脚本。

      NSDictionary* errorDict;
      NSAppleEventDescriptor* returnDescriptor = NULL;
      
      NSAppleScript* scriptObject;
      scriptObject = [[NSAppleScript alloc] initWithSource:@"try\n
      run application \"Macintosh HD:Applications:_Sandbox-AppleScript0.app\"\n
      on error number -609 # 'Connection is invalid' error that is spuriously reported # simply ignore\n
      end try"];
      
      if (returnDescriptor != NULL) {
           // successful execution
           if (kAENullEvent != [returnDescriptor descriptorType]) {
               // script returned an AppleScript result
               if (cAEList == [returnDescriptor descriptorType]) {
                   // result is a list of other descriptors
               }
               else {
                    // coerce the result to the appropriate ObjC type
               }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-06-23
        • 2015-07-21
        • 2012-02-13
        • 2011-08-30
        • 1970-01-01
        • 2011-03-27
        • 1970-01-01
        • 2013-02-05
        相关资源
        最近更新 更多