[英]How do I interrogate the current app's URL scheme programmatically?
My iOS app has 50+ targets, each with their own custom URL scheme. 我的iOS应用程序有50多个目标,每个目标都有自己的自定义URL方案。 I need to detect if a request from a webview matches the scheme of the currently running app. 我需要检测来自webview的请求是否与当前正在运行的应用程序的方案匹配。 In order to do this, I need to be able to interrogate the current app's URL scheme(s) from code. 为此,我需要能够从代码中查询当前应用程序的URL方案。
Similar questions deal with attempting to interrogate other apps to discover their URL schemes, which seems like it is not possible. 类似的问题涉及试图询问其他应用程序以发现其URL方案,这似乎是不可能的。 I need to find the scheme out for my own app, from within my app. 我需要在我的应用程序中找到我自己的应用程序的方案。
I would like to avoid having to set another plist value to the URL scheme and including that with the target. 我想避免为URL方案设置另一个plist值,并将其包含在目标中。
Is there any way to get the URL scheme of the current app? 有没有办法获得当前应用程序的URL方案?
This is the function I came up with to accomplish this. 这是我想出来实现这一目标的功能。
- (BOOL)doesMatchURLScheme:(NSString *)scheme {
if([[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleURLTypes"]) {
NSArray *urlTypes = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleURLTypes"];
for(NSDictionary *urlType in urlTypes)
{
if(urlType[@"CFBundleURLSchemes"])
{
NSArray *urlSchemes = urlType[@"CFBundleURLSchemes"];
for(NSString *urlScheme in urlSchemes)
if([urlScheme caseInsensitiveCompare:scheme] == NSOrderedSame)
return YES;
}
}
}
return NO;
}
In Swift 4 : Working version of getting the custom url scheme from Info.plist programmatically 在Swift 4中 : 以编程方式从Info.plist获取自定义URL方案的工作版本
func externalURLScheme() -> String? {
guard let urlTypes = Bundle.main.infoDictionary?["CFBundleURLTypes"] as? [AnyObject],
let urlTypeDictionary = urlTypes.first as? [String: AnyObject],
let urlSchemes = urlTypeDictionary["CFBundleURLSchemes"] as? [AnyObject],
let externalURLScheme = urlSchemes.first as? String else { return nil }
return externalURLScheme
}
(with the assumption that there is only 1 element in the urlTypes and urlSchemes array, hence taking the first element). (假设urlTypes和urlSchemes数组中只有1个元素,因此获取第一个元素)。 Here is my plist entry of URL Scheme 这是我的URL方案的plist条目
Extension for Bundle swift 4 syntax Bundle swift 4语法的扩展
extension Bundle {
static let externalURLSchemes: [String] = {
guard let urlTypes = main.infoDictionary?["CFBundleURLTypes"] as? [[String: Any]] else {
return []
}
var result: [String] = []
for urlTypeDictionary in urlTypes {
guard let urlSchemes = urlTypeDictionary["CFBundleURLSchemes"] as? [String] else { continue }
guard let externalURLScheme = urlSchemes.first else { continue }
result.append(externalURLScheme)
}
return result
}()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.