一、在 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/
相关资源:
-
Defining a Custom URL Scheme for Your App
https://developer.apple.com/documentation/uikit/inter-process_communication/allowing_apps_and_websites_to_link_to_your_content/defining_a_custom_url_scheme_for_your_app -
Allowing Apps and Websites to Link to Your Content
https://developer.apple.com/documentation/uikit/inter-process_communication/allowing_apps_and_websites_to_link_to_your_content?language=objc -
URL Schemes 使用详解
https://sspai.com/post/31500 -
入门 iOS 自动化:读懂 URL Schemes
https://sspai.com/post/44591