我想旋转 NSURLConnection 类的初始化初始化方法,我已经尝试过这段代码,但它似乎对我不起作用
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)
extension NSURLConnection{
public override class func initialize() {
struct Static {
static var token: dispatch_once_t = 0
}
if self !== NSURLConnection.self {
return
}
dispatch_once(&Static.token) {
let originalSelector = Selector("initWithRequest:delegate:startImmediately:")
let swizzledSelector = Selector("initWithTest: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
convenience init(test: NSURLRequest, delegate: AnyObject?, startImmediately: Bool){
print("Inside Swizzled Method")
self.init()
}
}
我认为有两件事必须解决:
如本回答所述,您应该在originalSelector
中使用 Objective-C 方法签名:
`let originalSelector = Selector("initWithRequest:delegate:startImmediately:")`
您不会从该方法返回任何内容my_init
。您应该返回与正在切换的方法相同的类型,在本例中为 NSURLConnection
.
func my_init(request: NSURLRequest, delegate: AnyObject?, startImmediately: Bool) -> NSURLConnection? {
print("Inside Swizzled Method")
//call the original initializer
return my_init( request, delegate: delegate, startImmediately: startImmediately)
}
您可以看到my_init
是在重排方法中调用的。在运行时中,它将调用原始initWithRequest:delegate:startImmediately
因为此时方法已经交换
最后但并非最不重要的一点是,NSURLConnection
在iOS 9中已弃用。强烈建议改用NSURLSession
,因为它更现代并且具有更多有用的功能。