ios – 如何在Swift 3中使用代理服务器的URLSession

前端之家收集整理的这篇文章主要介绍了ios – 如何在Swift 3中使用代理服务器的URLSession前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
对于API请求,我尝试使用代理设置URLSession.为了测试目的,我使用公共代理和响应IP的API.
func makeRequestViaUrlSessionProxy(_ url: String,completion: @escaping (_ result: String?) -> ()) {

    let request = URLRequest(url: URL(string: url)!)

    let config = URLSessionConfiguration.default
    config.requestCachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
    config.connectionProxyDictionary = [AnyHashable: Any]()
    config.connectionProxyDictionary?[kcfNetworkProxiesHTTPEnable as String] = 1
    config.connectionProxyDictionary?[kcfNetworkProxiesHTTPProxy as String] = "142.54.173.19"
    config.connectionProxyDictionary?[kcfNetworkProxiesHTTPPort as String] = 8888

    let session = URLSession.init(configuration: config,delegate: nil,delegateQueue: OperationQueue.current)

    let task = session.dataTask(with: request) {
        (data: Data?,response: URLResponse?,error: Error?) in
        if error != nil {
            NSLog("Client-side error in request to \(url): \(error)")
            completion(nil)
            return
        }

        if data == nil {
            NSLog("Data from request to \(url) is nil")
            completion(nil)
            return
        }

        let httpResponse = response as? HTTPURLResponse
        if httpResponse?.statusCode != 200 {
            NSLog("Server-side error in request to \(url): \(httpResponse)")
            completion(nil)
            return
        }

        let encodingName = response?.textEncodingName != nil ? response?.textEncodingName : "utf-8"
        let encoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding(encodingName as CFString!))
        let stringData = String(data: data!,encoding: String.Encoding(rawValue: UInt(encoding)))
        session.invalidateAndCancel()
        completion(stringData)
    }
    task.resume()
}

调用者:

override func viewDidLoad() {
    super.viewDidLoad()
    makeRequestViaUrlSessionProxy("https://api.ipify.org?format=json") { string in
        print(string)
    }
}

看起来配置完全被忽略了,因为即使使用了代理IP,响应IP始终是实际的设备IP

任何帮助是非常感谢.

编辑:按照用户hasan83的建议,采取“HTTPS密钥”似乎不是一个选择.


解决方法

我认为工作(应该被弃用)的键是:
kcfStreamPropertyHTTPSProxyHost
kcfStreamPropertyHTTPSProxyPort

你可以试试这个代码吗?

func makeRequestViaUrlSessionProxy(_ url: String,completion: @escaping (_ result: String?) -> ()) {

    let request = URLRequest(url: URL(string: url)!)

    let config = URLSessionConfiguration.default
    config.requestCachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
    config.connectionProxyDictionary = [AnyHashable: Any]()
    config.connectionProxyDictionary?[kcfNetworkProxiesHTTPEnable as String] = 1
    config.connectionProxyDictionary?[kcfNetworkProxiesHTTPProxy as String] = "142.54.173.19"
    config.connectionProxyDictionary?[kcfNetworkProxiesHTTPPort as String] = 8888
    config.connectionProxyDictionary?[kcfStreamPropertyHTTPSProxyHost as String] = "142.54.173.19"
    config.connectionProxyDictionary?[kcfStreamPropertyHTTPSProxyPort as String] = 8888

    let session = URLSession.init(configuration: config,encoding: String.Encoding(rawValue: UInt(encoding)))
        session.invalidateAndCancel()
        completion(stringData)
    }
    task.resume()
}

还请确保您的代理服务器配置为处理https请求.

注意:它可能会为这些键提供不推荐的警告,但键仍然工作(请参阅https://forums.developer.apple.com/thread/19356#131446)

原文链接:https://www.f2er.com/iOS/336716.html

猜你在找的iOS相关文章