有几件事可能会引起问题:
-
方法签名是不同的。原始实现没有
error
参数,但它是一个抛出函数。而且,与你的swizzled方法不同,
sendSynchronousRequest
URLRequest
而不是
NSURLRequest
.
-
您正在滑动一个实例和一个类方法。我不确定如何(或是否)使其发挥作用。
-
发送同步请求
作为投掷功能暴露于Swift。如果您的swizzled函数没有标记为
throws
以下是操场的一些工作代码:
import Foundation
import ObjectiveC
extension NSURLConnection {
@objc static func swizzSendSynchronousRequest(_ request: URLRequest?, returning response: URLResponse?) -> Data? {
print("Inside Sync Swizzled Method")
print("------------\(String(describing: request))")
return Data()
}
}
let originalRequestSyncSelector = #selector(NSURLConnection.sendSynchronousRequest(_:returning:))
let swizzledRequestSyncSelector = #selector(NSURLConnection.swizzSendSynchronousRequest(_:returning:))
let originalSyncRequestMethod = class_getClassMethod(NSURLConnection.self, originalRequestSyncSelector)
let swizzledSyncRequestMethod = class_getClassMethod(NSURLConnection.self, swizzledRequestSyncSelector)
method_exchangeImplementations(originalSyncRequestMethod!, swizzledSyncRequestMethod!)
let request = URLRequest(url: URL(string: "https://example.com")!)
do {
let data = try NSURLConnection.sendSynchronousRequest(request, returning: nil)
print(data)
} catch {
print(error)
}
无论如何,我认为在Objective-C中执行swizzling是一个更好的主意。
有
much better documentation
关于如何做到这一点,您可以避免Swift中的陷阱<-&燃气轮机;目标C桥接魔法。