MacOS 给自己的 app 添加 URL Scheme

来源:互联网 发布:nginx访问js报错403 编辑:程序博客网 时间:2024/05/18 20:33

  • 一在 Infoplist 中配置CFBundleURLTypesURL Types
  • 在 delegate 的 applicationDidFinishLaunching 中添加相应方法
  • 验证

一、在 Info.plist 中配置CFBundleURLTypes(URL Types)

source code 模式下的代码

<key>CFBundleURLTypes</key>    <array>        <dict>            <key>CFBundleURLName</key>            <string>com.MelissaShu.MSImagePick</string>            <key>CFBundleURLSchemes</key>            <array>                <string>ms</string>            </array>        </dict>    </array>

配置成功后如下
这里写图片描述


在 delegate 的 applicationDidFinishLaunching 中添加相应方法

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {    [[NSAppleEventManager sharedAppleEventManager] setEventHandler:self andSelector:@selector(handleURLEvent:withReplyEvent:) forEventClass:kInternetEventClass andEventID:kAEGetURL];}- (void)handleURLEvent:(NSAppleEventDescriptor*)theEvent withReplyEvent:(NSAppleEventDescriptor*)replyEvent {    NSString* path = [[theEvent paramDescriptorForKeyword:keyDirectObject] stringValue];    [[NSAlert alertWithMessageText:@"URL Request" defaultButton:@"OK" alternateButton:nil otherButton:nil informativeTextWithFormat:@"%@", path] runModal];}

验证

1、先让程序跑起来;
2、在浏览器中输入 ms://1 (1为随意填写,你也可以改为其他)
会弹出系统窗口,提示你是否打开 app;
这里写图片描述

3、点击打开后,会出现我们刚写的弹窗,提示刚输入的链接。

这里写图片描述

这就完成了


参考资料:http://cocoa.venj.me/blog/custom-url-scheme-on-mac-and-ios/

原创粉丝点击