使用NSAppleEventManager和kInternetEventClass/kAEGetURL的Cocoa协议处理程序

AJ.*_*.DE 12 url cocoa protocols objective-c handler

这是这个问题的Cocoa版本:

AEInstallEventHandler处理程序在启动时未被调用

这是我的Info.plist协议注册:

    ...
    <key>CFBundleURLTypes</key>
    <array>
        <dict>
            <key>CFBundleURLName</key>
            <string>My Protocol</string>
            <key>CFBundleURLIconFile</key>
            <string>myicon</string>
            <key>CFBundleTypeRole</key>
            <string>Viewer</string>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>myapp</string>
            </array>
        </dict>
    </array>
Run Code Online (Sandbox Code Playgroud)

这里是我设置方法来监听kInternetEventClass/kAEGetURL事件时单击浏览器链接"myapp:// unused /?a = 123&b = 456":

- (void)applicationDidFinishLaunching:(NSNotification *)notification
{
    [[NSAppleEventManager sharedAppleEventManager] setEventHandler:self andSelector:@selector(getURL:withReplyEvent:) forEventClass:kInternetEventClass andEventID:kAEGetURL];
    ...
}
Run Code Online (Sandbox Code Playgroud)

这是处理程序方法:

- (void)getURL:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)reply
{
    [[[event paramDescriptorForKeyword:keyDirectObject] stringValue] writeToFile:@"/testbed/complete_url.txt" atomically:YES];
}
Run Code Online (Sandbox Code Playgroud)

这是测试网站链接:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
</head>
<body>
    <a href="myapp://open/?a=123&b=456">Open My App</a>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

如果应用程序已在运行,这一切都很有效.

调用处理程序方法并捕获完整的URL.

但是,如果应用程序尚未运行,则相同的链接将启动应用程序,但不会调用处理程序 - 这是有道理的,因为处理程序尚未绑定到事件.

URL中的这些参数对于我们的应用程序与webapp协调非常重要.虽然绝大部分时间我们的应用程序在发生这种点击时已经运行,但是在某些情况下它不会发生这种情况是合理的.

我已经尝试检查环境和处理调用参数,我没有在其中任何一个中看到URL.

任何人都知道我们如何可靠地捕获此URL,即使我们的应用程序在浏览器点击发生时尚未运行时也是如此?

mik*_*ker 2

我刚刚遇到了这个问题。我不知道这是否是正确的解决方案,但您可以在应用程序委托的init方法中注册事件处理程序。

// in AppDelegate.m

- (id)init
{
  self = [super init];

  if (self) {
    [[NSAppleEventManager sharedAppleEventManager] setEventHandler:self andSelector:@selector(handleURLEvent:withReplyEvent:) forEventClass:kInternetEventClass andEventID:kAEGetURL];
  }

  return self;
}
Run Code Online (Sandbox Code Playgroud)

但需要注意的一件事是,如果应用程序是通过 URL 方案启动的,则get 会在之前handleURLEvent:withReplyEvent调用。 applicationDidFinishLaunching: