Swift 2 OSX How do I implement proxy settings with

2019-09-05 05:32发布

With iOS I was able to get as far as a 407 error requiring authorization. With OSX, no such luck. After the task resumes, it just hangs for a long time then reports that a connection couldn't be made.

If you answer, please also include how to pass proxy username and password.

func sendRequest() {
    var proxyHost :  CFString = NSString(string: "12.345.67.89") as CFString
    var proxyPort :  CFString = NSString(string: "1234") as CFString
    var proxyEnable :  CFNumber = NSNumber(int: 1) as CFNumber

    var proxyDict: [NSObject : AnyObject] = [
        kCFNetworkProxiesHTTPEnable: proxyEnable,
        kCFStreamPropertyHTTPProxyHost: proxyHost,
        kCFStreamPropertyHTTPProxyPort: proxyPort,
        kCFStreamPropertyHTTPSProxyHost: proxyHost,
        kCFStreamPropertyHTTPSProxyPort: proxyPort,
        kCFProxyTypeKey: kCFProxyTypeHTTPS
    ]
    let request = NSMutableURLRequest(URL: NSURL(string:https://www.someurl.com/login)) 
    var configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration()
    let configuration.connectionProxyDictionary = proxyDict
    let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: NSOperationQueue.mainQueue())

    let task = session.dataTaskWithRequest(request) {  (data, response, error) in
        NSHTTPCookieStorage.sharedHTTPCookieStorage().setCookies([NSHTTPCookie](), forURL: self.URL, mainDocumentURL: nil)

        if data != nil {
            do {
                let responseHeaders = response as! NSHTTPURLResponse
                self.statusCode = responseHeaders.statusCode

                switch self.statusCode {
                case 200:
                    self.contentsOfURL = try NSString(contentsOfURL: self.URL, encoding: NSUTF8StringEncoding)
                    self.cookies = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookiesForURL(self.URL)!
                    for cookie in self.cookies {
                        if cookie.name == "session" {
                            self.sessionCookie = cookie.value
                        }
                    }

                case 400:
                    print("400: page not found on web")

                case 404:
                    print("404: page not found on server")

                case 407:
                    print("407: failed authenticate proxy credentials")                 
                default:
                    print("unable to get statusCode")
                }
            } catch {

            }
        } else {
            print("\(self.statusCode): unable to get response ")
        }

        dispatch_semaphore_signal(semaphore)
    }
    task.resume()
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
}

0条回答
登录 后发表回答