Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setup proxy in Swift?

Tags:

ios

proxy

swift

I have just started using iOS technologies, and developing an iPhone application using Swift.
I am trying to query server using following code:

var url = NSURL(string: "http://someurl:8080/?type=Refresh")
var request = NSURLRequest(URL: url!)
var connection = NSURLConnection(request: request, delegate: self, startImmediately: true)

But I need to setup proxy on my iPhone device if I need to query that server. So now I want to setup http proxy (server and port) in Swift code itself.

I looked into CFProxySupport Reference by Apple, but not understanding how can I use it. I have written following code till now:

var proxy_server: CFString = “proxy” // proxy server
var proxy_port: CFNumber = 8080 // port

var keys: [CFStringRef] = [kCFProxyTypeKey, kCFProxyHostNameKey, kCFProxyPortNumberKey]
var values: [CFTypeRef] = [kCFProxyTypeHTTP, proxy_server, proxy_port]

var proxy_dict: CFDictionary = CFDictionaryCreate(
    kCFAllocatorDefault,
    UnsafeMutablePointer<UnsafePointer<Void>>(keys),
    UnsafeMutablePointer<UnsafePointer<Void>>(values),
    3,
    nil,
    nil)

var proxies: Unmanaged<CFArray> = CFNetworkCopyProxiesForURL(NSURL(string: "http://someurl:8080"), proxy_dict)

Can anyone please tell me how to use proxies to setup proxy?
Thanks!

like image 453
user2312896 Avatar asked Dec 17 '14 14:12

user2312896


1 Answers

The CFProxySupport framework allows your app to retrieve proxies that have been configured in the device. Some of these proxy configurations may actually be a auto proxy config URL/script - so CFNetworkCopyProxiesForURL may evaluate these scripts to the determine the proxies that apply to the specified URL.

CFProxySupport does not allow you to configure the proxies that the device will use. Further, NSURLConnection doesn't honour the device proxy settings. You can use the code you have to retrieve the configured proxy and then use this with a library, such as NSURLSession or AFNetworking, that does support the use of a proxy server. In NSURLSession you specify the proxy configuration in the connectionProxy dictionary of the NSURLSessionConfiguration object

like image 137
Paulw11 Avatar answered Sep 20 '22 09:09

Paulw11