我正在为我的一个应用程序实现一个自定义URL方案,但无法使其工作。
我把这些行添加到我的Info.plist中:
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLName</key>
<string>MyApp URL</string>
<key>CFBundleURLSchemes</key>
<array>
<string>myscheme</string>
</array>
</dict>
</array>
在我的应用程序代理中,我在ApplicationDidFinishedLaunching:中安装了事件处理程序
NSAppleEventManager *appleEventManager = [NSAppleEventManager sharedAppleEventManager];
[appleEventManager setEventHandler:self andSelector:@selector(handleGetURLEvent:withReplyEvent:) forEventClass:kInternetEventClass andEventID:kAEGetURL];
但当我点击URL为例如的链接时,不会调用该方法。"myscheme://test"
- (void)handleGetURLEvent:(NSAppleEventDescriptor *)event
withReplyEvent:(NSAppleEventDescriptor *)replyEvent {
// Extract the URL from the Apple event and handle it here.
NSString* url = [[event paramDescriptorForKeyword:keyDirectObject] stringValue];
NSLog(@"%@", url);
}
我错过了什么?
听起来你可能需要清理你的项目。有时,当Xcode构建应用程序时,Launch Services数据库(处理URL关联)没有正确更新。清理项目应该会完全删除已生成的应用程序,因此下次生成项目时,它将在更新启动服务数据库的过程中从头开始创建。
您可能还想尝试将应用程序复制到/Applications
文件夹中,这将使Launch Services重新解析应用程序的Info.plist
文件。
您可以通过在终端中运行以下命令来强制启动服务重建其数据库:
/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister -kill -r -domain local -domain system -domain user
将事件处理程序代码移动到init
方法:
- (id) init
{
if ((self = [super init]))
{
NSAppleEventManager *appleEventManager = [NSAppleEventManager sharedAppleEventManager];
[appleEventManager setEventHandler:self andSelector:@selector(handleGetURLEvent:withReplyEvent:) forEventClass:kInternetEventClass andEventID:kAEGetURL];
// Add the following to set your app as the default for this scheme
NSString * bundleID = [[NSBundle mainBundle] bundleIdentifier];
LSSetDefaultHandlerForURLScheme((CFStringRef)@"myscheme", (CFStringRef)bundleID
}
return self;
}
注意:myscheme
应该采用x-com-companyname-appname
的形式,这样它就不会与任何其他方案发生冲突。
另请参阅:有关此主题的更多信息,请参阅如何将您的Cocoa应用程序设置为默认web浏览器?
更新数据库OS10.8 Mountain Lion
/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregger-f
-kill Reset the Launch Services database before doing anything else
-seed If database isn't seeded, scan default locations for applications
and libraries to register
-lint Print information about plist errors while registering bundles
-convert Register apps found in older LS database files
-lazy n Sleep for n seconds before registering/scanning
-r Recursive directory scan, do not recurse into packages or invisible
directories
-R Recursive directory scan, descending into packages and invisible
directories
-f force-update registration even if mod date is unchanged
-u unregister instead of register
-v Display progress information
-dump Display full database contents after registration
-h Display this help
显然,在沙箱下,您需要在applicationWillFinishLaunching:中注册,而不是在applicationDidFinishLaunching:中注册
请参阅苹果的文档。