我一直在尝试为要使用 afnetworking 在我的 webView 中打开的链接添加代理。我正在设置 webview,但我需要使用代理加载 webview 的内容。你们中的任何人都知道如何在 NSURLRequest 中实现代理吗?我所做的是这样的:
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 2
NSString* proxyHost = @"xxx.xxx.xx.x.";
NSNumber* proxyPort = @"Myport";
// Create an NSURLSessionConfiguration that uses the proxy
NSDictionary *proxyDict = @{
(NSString *)( kCFNetworkProxiesHTTPEnable):[NSNumber numberWithInt:1],
(NSString *)(kCFNetworkProxiesHTTPProxy):proxyHost,
(NSString *)(kCFNetworkProxiesHTTPPort):proxyPort
};
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
configuration.connectionProxyDictionary = proxyDict;
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(@"Error: %@", error);
} else {
NSLog(@"%@ %@", response, responseObject);
}
}];
[dataTask resume];
但同样没有给我任何东西,只是给出了超时错误。 所以请帮助找到相同的解决方案
import UIKit
import CoreFoundation
class SpecialProtocol: NSURLProtocol, NSURLSessionDataDelegate, NSURLSessionTaskDelegate {
//var httpMessageRef: CFHTTPMessage;()
var httpMessageRef: CFHTTPMessage?
class func registerSpecialProtocol() {
var inited: Bool = false
if !inited {
NSURLProtocol.registerClass(SpecialProtocol.self)
inited = true
}
}
private var dataTask:NSURLSessionDataTask?
private var urlResponse:NSURLResponse?
private var receivedData:NSMutableData?
class var CustomKey:String {
return "myCustomKey"
}
// MARK: NSURLProtocol
override class func canInitWithRequest(request: NSURLRequest) -> Bool {
if (NSURLProtocol.propertyForKey(SpecialProtocol.CustomKey, inRequest: request) != nil) {
return false
}
return true
}
override class func canonicalRequestForRequest(request: NSURLRequest) -> NSURLRequest {
return request
}
override func startLoading() {
let newRequest = self.request.mutableCopy() as! NSMutableURLRequest
NSURLProtocol.setProperty("true", forKey: SpecialProtocol.CustomKey, inRequest: newRequest)
let defaultConfigObj = customizeEphemeralSessionConfiguration()//NSURLSessionConfiguration.defaultSessionConfiguration()
let defaultSession = NSURLSession(configuration: defaultConfigObj, delegate: self, delegateQueue: nil)
self.dataTask = defaultSession.dataTaskWithRequest(newRequest)
self.dataTask!.resume()
}
func customizeEphemeralSessionConfiguration() -> NSURLSessionConfiguration {
let proxy_server: CFString = "myProxyServer.com" // proxy server
let proxy_port: CFNumber = 1234 // port
let hostKey: NSString = kCFNetworkProxiesHTTPProxy as NSString
let portKey: NSString = kCFNetworkProxiesHTTPPort as NSString
let proxyDict:[String:AnyObject] = [kCFNetworkProxiesHTTPEnable as String: true, hostKey as String:proxy_server, portKey as String: proxy_port]
let config = NSURLSessionConfiguration.ephemeralSessionConfiguration()
config.connectionProxyDictionary = proxyDict as [NSObject : AnyObject]
return config
}
override func stopLoading() {
self.dataTask?.cancel()
self.dataTask = nil
self.receivedData = nil
self.urlResponse = nil
}
// MARK: NSURLSessionDataDelegate
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask,
didReceiveResponse response: NSURLResponse,
completionHandler: (NSURLSessionResponseDisposition) -> Void) {
self.client?.URLProtocol(self, didReceiveResponse: response, cacheStoragePolicy: .NotAllowed)
self.urlResponse = response
self.receivedData = NSMutableData()
completionHandler(.Allow)
}
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
self.client?.URLProtocol(self, didLoadData: data)
self.receivedData?.appendData(data)
}
// MARK: NSURLSessionTaskDelegate
func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
if error != nil && error!.code != NSURLErrorCancelled {
self.client?.URLProtocol(self, didFailWithError: error!)
} else {
saveCachedResponse()
self.client?.URLProtocolDidFinishLoading(self)
}
}
// MARK: Private methods
/**
Do whatever with the data here
*/
func saveCachedResponse () {
let timeStamp = NSDate()
let urlString = self.request.URL?.absoluteString
let dataString = NSString(data: self.receivedData!, encoding: NSUTF8StringEncoding) as NSString?
print("TimeStamp:\(timeStamp)\nURL: \(urlString)\n\nDATA:\(dataString)\n\n")
}
}
用法:
@IBOutlet weak var sWebViewOutlet : UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
setupViewDidLoad()
}
func setupViewDidLoad() {
SpecialProtocol.registerSpecialProtocol()
let url = NSURL(string: "http://www.google.com")
let req = NSURLRequest(URL: url!)
/* if this request will be handled by our special protocol... */
//if ( [SpecialProtocol canInitWithRequest:request] ) {
if SpecialProtocol.canInitWithRequest(req) {
print("SpecialProtocol.canInitWithRequest(req)")
self.sWebViewOutlet.loadRequest(req)
}
else {
print("SpecialProtocol.cantInitWithRequest(req)")
}
}
关于ios - 如何使用 afnetworking 将代理添加到请求中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38343970/
欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://jike.in/) | Powered by Discuz! X3.4 |