NSString *customURL = @"mycustomurl://";
if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:customURL]]) {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:customURL]];
} else {
...
}
即使未安装公开自定义 URL 的目标应用程序,应用程序也会为“canOpenURL”返回 true。此行为发生在手机和模拟器上。 openURL 然后默默地失败。任何想法为什么会发生这种情况/如何捕捉这种情况?
最佳答案
如果使用带有 SDK 9.0 及更高版本的应用程序,则必须确保在主应用程序的 info.plist 中添加要打开的应用程序方案:
如果不将上述内容添加到主应用程序的 info.plist(相应地更改方案),canOpenURL 将始终返回 NO。除非使用 iOS SDK 低于 9.0 的应用程序,否则它不会发生。
另外,请使用以下逻辑,因为它更安全:
NSString * urlStr = @"mycustomurl://";
NSURL * url = [NSURL URLWithString:urlStr];
if ([[UIApplication sharedApplication] canOpenURL:url]) {
if([[UIApplication sharedApplication] openURL:url]) {
// App opened
} else {
// App not opened
}
} else {
// Can not open URL
}
最后检查我建议是在设备中打开 Safari 应用程序,在 url 字段中输入应用程序方案 url 字符串,然后按 Enter。从结果中得出如何进行。