加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift – 如何使用默认的URL方案处理

发布时间:2020-12-14 05:57:33 所属栏目:百科 来源:网络整理
导读:我想在我的应用程序中构建URI(或URL方案)支持。 我在我的(void)初始化中做了一个LSSetDefaultHandlerForURLScheme(),我也在我的info.plist中设置了特定的URL方案。所以我有没有Apple Script或Apple Events的URL方案。 当我打电话给myScheme:在我最喜欢的浏
我想在我的应用程序中构建URI(或URL方案)支持。

我在我的(void)初始化中做了一个LSSetDefaultHandlerForURLScheme(),我也在我的info.plist中设置了特定的URL方案。所以我有没有Apple Script或Apple Events的URL方案。

当我打电话给myScheme:在我最喜欢的浏览器中,系统激活我的应用程序。

问题在于如何处理这些方案。或者更好的说:当我的程序被调用时,如何定义应用程序应该做什么?

有没有一个特殊的方法,我必须实现或我必须在某个地方注册一个?

正如你所提到的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>

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

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

每当您的应用程序通过URL方案激活时,定义的选择器将被调用。

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

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

苹果文档:Installing a 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);
}

在iPhone上,处理URL方案激活的最简单方法是实现UIApplicationDelegate的应用程序:handleOpenURL: – Documentation

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读