【问题标题】:How to swizzle URLSession class method dataTask in swift 3如何在 swift 3 中调整 URLSession 类方法 dataTask
【发布时间】:2017-05-01 10:39:34
【问题描述】:

我想调配 URLSession 类方法 dataTask 但无法完成。

我在 Objective-c 中尝试了这种 swizzling 并且它工作正常,现在我想在 swift 3 中实现它但没有得到任何东西。

我指的是 this 链接,但它在 swift 3 中不起作用。

请帮助我。

【问题讨论】:

  • 你想通过混合方法来实现什么?您是在编写测​​试用例并想替换 URL 调用还是只是调试?
  • @JohnDough 我正在寻找一种方法来实现这一点。有什么想法吗?

标签: swift swift3 method-swizzling


【解决方案1】:

我们可以像下面这样在swift中调配方法

let selectorfirst = #selector(ClassName.function(_:))
let swizzledFunction = #selector(ClassName.function2(_:))

let method1 = class_getInstanceMethod(ClassInstance, selectorfirst)
let method2 = class_getInstanceMethod(ClassInstance, swizzledFunction)

method_exchangeImplementations(method1, method2) 

//使用子类试试这样

     class URLSessionSubClass: URLSession {
static var sharedInstance: URLSessionSubClass?
static func getSharedInstance() -> URLSessionSubClass {
    if sharedInstance == nil {
        sharedInstance = URLSessionSubClass()
        let selectorfirst = #selector(URLSessionSubClass.function(_:))
        let swizzledFunction = #selector(URLSessionSubClass.function2(_:))

        let method1 = class_getInstanceMethod(self, selectorfirst)
        let method2 = class_getInstanceMethod(self, swizzledFunction)

        method_exchangeImplementations(method1, method2)
    }
    return sharedInstance!
}
}

【讨论】:

  • 请提供使用 URLSession 扩展的解决方案。
【解决方案2】:

我尝试过简单的 NSURLSession swizzling,它确实有效,但是在尝试实现 Alamorfire 和其他第三方网络 SDK 的 swizzling 时,它不起作用,因为我们需要从 URLProtocol 的基础进行 swizzling,实现 URLSessionConfiguration.default使用 swizzling 方法并添加所有属性,如 startLoading、stopLoading、init 和 canInit 功能。还要添加 URLSession 委托方法以返回值。

https://gist.github.com/nil-biribiri/ceead941d5b482207cb1b872c5d76a60

【讨论】:

    猜你喜欢
    • 2017-12-01
    • 2018-06-18
    • 1970-01-01
    • 2017-09-06
    • 2017-01-30
    • 1970-01-01
    • 1970-01-01
    • 2017-04-05
    • 1970-01-01
    相关资源
    最近更新 更多