我已经为NSURLConnection创建了sendSynchronousRequest方法swizzling,但是它在下面不起作用是我的代码。每当我试图从主要功能调用它时,它就崩溃了。
let originalRequestSyncSelector = #selector(self.sendSynchronousRequest(_:returning:))
let swizzledRequestSyncSelector = #selector(self.swizzSendSynchronousRequest(_:returning:error:))
let originalSyncRequestMethod = class_getClassMethod(self, originalRequestSyncSelector)
let swizzledSyncRequestMethod = class_getInstanceMethod(self, swizzledRequestSyncSelector)
if originalSyncRequestMethod == nil || swizzledSyncRequestMethod == nil {
return
}
method_exchangeImplementations(originalSyncRequestMethod!, swizzledSyncRequestMethod!)
@objc func swizzSendSynchronousRequest(_ request: NSURLRequest?, returning response: URLResponse?, error: Error?) -> Data? {
var tempData: Data?
print("Inside Sync Swizzled Method")
print("------------\(String(describing: request))")
return tempData
}发布于 2018-12-28 08:03:30
有几件事可能会引起问题:
error参数,而是一个抛出函数。而且,与您的swizzled方法不同,sendSynchronousRequest采用URLRequest而不是NSURLRequest。sendSynchronousRequest作为抛出函数公开给Swift。如果您的swizzled函数没有用throws标记,但是抛出函数不能暴露在ObjC中,并且可能会在被抛出时引起问题,它就能工作。以下是操场的一些工作代码:
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)
}无论如何,我认为在目标C中执行摆动是一个更好的主意。有关于如何做到这一点的更好的文档,您可以避免Swift <-> Objective桥接魔术中的陷阱。
https://stackoverflow.com/questions/53955043
复制相似问题