以编程方式读取iPhone代理设置

3

我正在考虑为我的iPhone SVN客户端添加代理支持。在iPhone设置中设置系统范围的VPN时,可以添加全局代理。外部应用程序是否可以通过API读取此信息?

4个回答

6
一个Swift 4版本(特别感谢mortehu提供的初始示例)。
//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]))")
    }
}

对于那些想知道的人,你可以像这样访问主机名和端口号:proxy[kCFProxyHostNameKey] | proxy[kCFProxyPortNumberKey] - mxlhz

6

苹果创建了一个样例应用程序,名为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' */

0

请看一下CFProxySupport API,特别是CFNetworkCopyProxiesForURL()函数,它可以让你读取到连接到某个URL所需的代理。


0

你有没有考虑使用类似ASIHttpRequest这样的东西?请参阅如何文档中描述代理支持的部分。

至少源代码应该包含一些有用的指导。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接