使用 webView 通过代理加载网页

1.首先要使用框架ASIHttpRequest,这是一个已经停止更新的框架
2.自定义一个实现 NSURLProtocol 和 ASIHTTPRequestDelegate 的类

import UIKit

class ProxyProtocol: NSURLProtocol,ASIHTTPRequestDelegate {
    override class func canInitWithRequest(request: NSURLRequest) -> Bool {
        requestWithMyProxy(request.URL!)
        return false
    }

    class func requestWithMyProxy(url:NSURL) -> String?{
        var responseString:String? = nil
        let request = ASIHTTPRequest.requestWithURL(url) as! ASIHTTPRequest
        request.delegate = self

        request.proxyHost = PROXY_SERVERHOST
        request.proxyPort = PROXY_SERVERPORT
        request.proxyUsername = PROXY_USERNAME
        request.proxyPassword = PROXY_PASSWORD
        request.shouldPresentAuthenticationDialog = true
        request.shouldPresentCredentialsBeforeChallenge = true
        request.shouldPresentProxyAuthenticationDialog = true

        request.startSynchronous()
        let requestError = request.error
        if requestError != nil {
            print("error: \(requestError)")
        }else {
            responseString = request.responseString()
        }
        return responseString
    }
}

3.在使用 webView 加载页面时判断是否使用代理

public func loadURLForWebView(pageUrl:String, webView:UIWebView) {
    proxyCheck()
    let url = NSURL(string: pageUrl)
    let request = NSURLRequest(URL: url!)
    webView.loadRequest(request)
    webView.scrollView.showsHorizontalScrollIndicator = false
    webView.scrollView.showsVerticalScrollIndicator = false
}

private func proxyCheck(){
    if isLogin {
        let vipFlag = getLocalValueFromNSUserDefaults("vipFlag") as? String
        if vipFlag == "1" {
            NSURLProtocol.registerClass(ProxyProtocol)
            PROXY_FLAG = true
            return
        }
    }
    NSURLProtocol.unregisterClass(ProxyProtocol)
    PROXY_FLAG = false
}

参考资料:

  1. NSURLProtocol Tutorial. 中文版
  2. 转 NSURLProtocol和NSRunLoop的那些坑
2015-10-09 19:0213