问题
NSString *customURL = @"mycustomurl://";
if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:customURL]]) {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:customURL]];
} else {
...
}
The app returns true for 'canOpenURL', even if the target app that exposes the custom URL is not installed. This behaviour occurs on both phone & simulator. openURL then silently fails. Any ideas why this is happening/how to catch this condition?
回答1:
If using an app with SDK 9.0 and up, then you will have to make sure to add the app schemes you want to open in your main app's info.plist:
Without adding the above to the main app's info.plist (change schemes accordingly) canOpenURL will always return NO. Unless using an app with iOS SDK lower then 9.0 then it won't happen.
Also, use the following logic as it is safer:
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
}
Last check I suggest is to open Safari app in the device, enter the app scheme url string in the url field, press enter. Conclude from the result how to proceed.
回答2:
Ensure that you are using instead LSApplicationQueriesSchemes of URL types
It works well only for LSApplicationQueriesSchemes
This will not work
This will work
回答3:
This is what i have used to open Uber app if it is installed else open Uber Website
if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"uber://"]])
{
//Uber is installed
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"uber://"]];
}
else
{
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://uber.com"]];
}
Do not forget to add this LSApplicationQueriesSchemes in your info.plist file
Like this (the names of the app uber and twitter has been included in this) info.plist screenshot
来源:https://stackoverflow.com/questions/34149611/canopenurl-returning-true-for-custom-url-scheme-even-if-app-is-not-installed