我想调整 NSURLConnection 类的 init init 方法,我已经尝试过这段代码,但它似乎对我不起作用
extension NSURLConnection{
public override class func initialize() {
struct Static {
static var token: dispatch_once_t = 0
}
dispatch_once(&Static.token) {
let originalSelector = Selector("init:delegate:startImmediately:")
let swizzledSelector = Selector("my_init:delegate:startImmediately:")
let originalMethod = class_getInstanceMethod(self, originalSelector)
let swizzledMethod = class_getInstanceMethod(self, swizzledSelector)
let didAddMethod = class_addMethod(self, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))
if didAddMethod {
class_replaceMethod(self, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod))
} else {
method_exchangeImplementations(originalMethod, swizzledMethod)
}
}
}
// MARK: - Method Swizzling
func my_init(request: NSURLRequest, delegate: AnyObject?, startImmediately: Bool){
print("Inside Swizzled Method")
}
}
这是我从视图控制器发起的请求
let testPoint: String = "www.google.com"
guard let url = NSURL(string: testPoint) else {
print("Error: cannot create URL")
return
}
let urlRequest = NSURLRequest(URL: url)
let conn = NSURLConnection(request: urlRequest, delegate: self, startImmediately: true)