macOS 开发 - 给 app 添加 URL Scheme


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

你可以在 Target --> Info --> URL Types 中添加,添加成功后将会在下面 info.plist 中生成下面结构的数据;也可以直接将下面数据拷贝到你的 info.plist:

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

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


二、在 delegate 添加 handle 方法

注意应该在 applicationWillFinishLaunching 中添加 setEventHandler 方法;
如果添加在 applicationDidFinishLaunching 中,未启动应用状态下,用 url 启动应用,不会调起 handleURLEvent 方法。

- (void)applicationWillFinishLaunching:(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/

相关资源:

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

编程乐园

请我喝杯伯爵奶茶~!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值