我正在考虑为我的iPhone SVN客户端添加代理支持。在iPhone设置中设置系统范围的VPN时,可以添加全局代理。外部应用程序是否可以通过API读取此信息?
//Shown this way for clarity, you may not want to waste cycles in your production code
if let url = URL(string: "https://someurloutthere.com") {
let systemProxySettings = CFNetworkCopySystemProxySettings()?.takeUnretainedValue() ?? [:] as CFDictionary
let proxiesForTargetUrl = CFNetworkCopyProxiesForURL(url as CFURL, systemProxySettings).takeUnretainedValue() as? [[AnyHashable: Any]] ?? []
for proxy in proxiesForTargetUrl {
print("Proxy: \(String(describing: proxy))")
//Print the proxy type
print("Proxy Type: \(String(describing: proxy[kCFProxyTypeKey]))")
//There different proxy value keys depending on the type, this is an example of getting the proxy config script if the type is kCFProxyTypeAutoConfigurationURL. If the proxy type were kCFProxyTypeSOCKS you would want to access the SOCKS property keys to see/get the SOCKS proxy values
print("Proxy Autoconfig script URL: \(String(describing: proxy[kCFProxyAutoConfigurationURLKey]))")
}
}
苹果创建了一个样例应用程序,名为CFProxySupportTool,用于此目的。
CFProxySupportTool展示了如何使用CFProxySupport API来确定网络连接是否应该通过代理传递;如果您没有使用苹果的高级网络API(如CFNetwork和基础URL加载系统),但仍想解释系统提供的代理设置,则此功能非常有用。
它目前可在https://developer.apple.com/library/mac/#samplecode/CFProxySupportTool/Introduction/Intro.html上获得。
代码并不是特别简洁(超过1000行),并且是用纯C编写的。您还可以查看ASIHTTPRequest的startRequest函数的源代码,它似乎是基于CFProxySupportTool编写的。
这里是一个开端:
systemProxySettings = [(NSDictionary *) CFNetworkCopySystemProxySettings() autorelease];
proxies = [(NSArray *) CFNetworkCopyProxiesForURL((CFURLRef) URL, (CFDictionaryRef) systemProxySettings) autorelease];
if (!proxies.count)
return;
firstProxySettings = [proxies objectAtIndex:0];
if (nil != (pacScriptURL = [firstProxySettings objectForKey:(NSString *)kCFProxyAutoConfigurationURLKey]))
{
CFErrorRef cfErrorRef = NULL;
NSError *nsError = nil;
NSString *script;
script = [NSString stringWithContentsOfURL:pacScriptURL
usedEncoding:NULL
error:&nsError];
if (nsError)
return;
proxies = [(NSArray *) CFNetworkCopyProxiesForAutoConfigurationScript((CFStringRef) script, (CFURLRef) URL, &cfErrorRef) autorelease];
if (cfErrorRef || !proxies.count)
return;
firstProxySettings = [proxies objectAtIndex:0];
}
/* Now use `firstProxySettings' */
proxy[kCFProxyHostNameKey]
|proxy[kCFProxyPortNumberKey]
- mxlhz