代码之家  ›  专栏  ›  技术社区  ›  jlstrecker

如何使用自定义URL方案将获取URL事件发送到正在运行的应用程序?

  •  3
  • jlstrecker  · 技术社区  · 14 年前

    我的cocoa应用程序需要处理get url事件。我想我正确地遵循了 this answer 要修改info.plist并写入&注册URL处理程序方法。

    问题:

    1. 当我在我的应用程序运行时访问mytesturl://safari中的任何内容时,它会弹出一个窗口,询问我是否要打开我的应用程序。如果我说是的话,除了一个图标在码头上出现一瞬间之外,似乎什么都没有发生。所以它可能试图启动我的应用程序的另一个实例,而不是向正在运行的实例发送消息?

    2. 当我在火狐中做同样的操作时,它会弹出一个窗口,要求我选择一个应用程序。所以定制的URL协议不应该在所有浏览器中都起作用?

    信息列表:

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
    <dict>
        ...
        <key>CFBundleURLTypes</key>
        <array>
            <dict>
                <key>CFBundleURLName</key>
                <string>My test URL</string>
                <key>CFBundleURLSchemes</key>
                <array>
                    <string>mytesturl</string>
                </array>
            </dict>
        </array>
         ...
    </dict>
    </plist>
    

    源代码:

    #import <Cocoa/Cocoa.h>
    #include <stdio.h>
    
    @interface Test : NSObject
    {
    }
    - (void)test;
    - (void)handleEvent:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent; 
    @end
    
    @implementation Test
    - (void)test
    {
        NSLog(@"Started..."); 
        char c; 
        scanf("%c", &c); 
    }
    
    - (void)handleEvent:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent
    {
        NSURL *url = [NSURL URLWithString:[[event paramDescriptorForKeyword:keyDirectObject] stringValue]];
        NSLog(@"url = %@", url); 
    }
    @end
    
    int main(int argc, char *argv[])
    {
        Test *app=[[Test alloc] init];
        [[NSAppleEventManager sharedAppleEventManager] setEventHandler:app andSelector:@selector(handleEvent:withReplyEvent:) forEventClass:kInternetEventClass andEventID:kAEGetURL];
    
        [app test];
    
        return 0;   
    }
    
    1 回复  |  直到 14 年前
        1
  •  2
  •   smokris    14 年前

    NSAppleEventManager NSApplication

    Test main

     id app = [NSApplication sharedApplication];
     [[NSAppleEventManager sharedAppleEventManager] setEventHandler:app andSelector:@selector(handleEvent:withReplyEvent:) forEventClass:kInternetEventClass andEventID:kAEGetURL];
     [app run];