Skip to content

Commit

Permalink
Added using system proxy. (Except for linux)
Browse files Browse the repository at this point in the history
  • Loading branch information
OrkhanAlikhanov committed Jul 15, 2017
1 parent e15645c commit 0fa3563
Showing 1 changed file with 34 additions and 1 deletion.
35 changes: 34 additions & 1 deletion Sources/Client.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,40 @@ open class Client {
let queue = DispatchQueue(label: "com.biatoms.request-swift." + UUID().uuidString)
var firesImmediately: Bool = true
var timeout: Int = 5000 // in ms

var usesSystemProxy: Bool = true
var proxy: Proxy? = nil

public init(baseUrl: String? = nil) {
public init(baseUrl: String? = nil, usesSystemProxy: Bool = true) {
self.baseUrl = baseUrl
}

//https://forums.developer.apple.com/thread/65416
open static func getSystemProxy(for host: String) -> Proxy? {
#if os(Linux) //CFNetworkCopySystemProxySettings hasn't been implemented. (see https://github.com/apple/swift-corelibs-foundation)
#else
if let url = URL(string: host) {
if let proxySettingsUnmanaged = CFNetworkCopySystemProxySettings() {
let proxySettings = proxySettingsUnmanaged.takeRetainedValue()
let proxiesUnmanaged = CFNetworkCopyProxiesForURL(url as CFURL, proxySettings)
let proxies = proxiesUnmanaged.takeRetainedValue() as! [[String:AnyObject]]

for dict in proxies {
if let type = dict[kCFProxyTypeKey as String] {
if type as! CFString == kCFProxyTypeHTTP { //only http for now
let host = dict[kCFProxyHostNameKey as String] as! String
let port = (dict[kCFProxyPortNumberKey as String] as! NSNumber).intValue
return (host, Port(port))
}
}
}

}
}
#endif
return nil
}


open func request(_ url: String, method: Request.Method = .get, parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: Headers? = nil)
-> Requester
Expand All @@ -42,6 +70,11 @@ open class Client {

let request = Request(method: method, url: url, headers: headers ?? [:], body: [])
encoding.encode(request, with: parameters)
var proxy = self.proxy
if usesSystemProxy {
proxy = Client.getSystemProxy(for: url)
}

let requester = Requester(request: request, queue: queue, timeout: timeout, proxy: proxy)

if firesImmediately {
Expand Down

0 comments on commit 0fa3563

Please sign in to comment.