如何使用默认URL方案处理

pap*_*apr 23 macos cocoa url-scheme appkit

我想在我的应用程序中构建URI(或URL方案)支持.

LSSetDefaultHandlerForURLScheme()在我的工作中+ (void)initialize也设置了特定的URL方案info.plist.所以我没有Apple Script或没有URL方案Apple Events.

当我myScheme:在我最喜欢的浏览器中调用时,系统会激活我的应用程序.

问题是,如何在调用方案时处理这些方案.或者更好地说:如何定义应用程序应该执行的操作,何时myScheme:调用.

有一种特殊的方法我必须实现或者我必须在某处注册吗?

Tho*_*ing 70

正如您提到的AppleScript,我想您正在使用Mac OS X.

注册和使用自定义URL方案的一种简单方法是在.plist中定义方案:

<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLName</key>
        <string>URLHandlerTestApp</string>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>urlHandlerTestApp</string>
        </array>
    </dict>
</array>
Run Code Online (Sandbox Code Playgroud)

要注册该方案,请将其放入AppDelegate的初始化中:

[[NSAppleEventManager sharedAppleEventManager]
    setEventHandler:self
        andSelector:@selector(handleURLEvent:withReplyEvent:)
      forEventClass:kInternetEventClass
         andEventID:kAEGetURL];
Run Code Online (Sandbox Code Playgroud)

每当您的应用程序通过URL方案激活时,都会调用定义的选择器.

事件处理方法的存根,显示如何获取URL字符串:

- (void)handleURLEvent:(NSAppleEventDescriptor*)event
        withReplyEvent:(NSAppleEventDescriptor*)replyEvent
{
    NSString* url = [[event paramDescriptorForKeyword:keyDirectObject]
                        stringValue];
    NSLog(@"%@", url);
}
Run Code Online (Sandbox Code Playgroud)

Apple的文档:安装Get URL Handler

更新 我刚发现安装事件处理程序的沙盒应用程序存在问题applicationDidFinishLaunching:.启用沙盒后,通过单击使用自定义方案的URL启动应用程序时,不会调用处理程序方法.通过稍早安装处理程序applicationWillFinishLaunching:,该方法按预期调用:

- (void)applicationWillFinishLaunching:(NSNotification *)aNotification
{
    [[NSAppleEventManager sharedAppleEventManager]
        setEventHandler:self
            andSelector:@selector(handleURLEvent:withReplyEvent:)
          forEventClass:kInternetEventClass
             andEventID:kAEGetURL];
}

- (void)handleURLEvent:(NSAppleEventDescriptor*)event
        withReplyEvent:(NSAppleEventDescriptor*)replyEvent
{
    NSString* url = [[event paramDescriptorForKeyword:keyDirectObject]
                        stringValue];
    NSLog(@"%@", url);
}
Run Code Online (Sandbox Code Playgroud)

在iPhone上,处理URL方案激活的最简单方法是实现UIApplicationDelegate的application:handleOpenURL:- 文档


Lai*_*mis 7

所有的学分应该去weichselKCH

我只是添加了swift(2.2/3.0)代码以方便您使用

func applicationWillFinishLaunching(_ notification: Notification) {
    NSAppleEventManager.shared().setEventHandler(self, andSelector: #selector(self.handleGetURL(event:reply:)), forEventClass: UInt32(kInternetEventClass), andEventID: UInt32(kAEGetURL) )
}

func handleGetURL(event: NSAppleEventDescriptor, reply:NSAppleEventDescriptor) {
    if let urlString = event.paramDescriptor(forKeyword: keyDirectObject)?.stringValue {
        print("got urlString \(urlString)")
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 您知道是否有办法避免应用程序在收到 URL 时被激活并发送到前台? (2认同)

Pet*_*sey 5

问题是,如何在调用方案时处理这些方案.

这就是Apple Events的用武之地.当Launch Services希望你的应用打开一个URL时,它会向你的应用发送一个kInternetEventClass/ kAEGetURLevent.

Cocoa脚本指南使用此任务作为安装事件处理程序的示例.