1

I want to swizzle URLSession class method dataTask but not been able to get it done.

I tried this swizzling in objective-c and its working fine in that now I want to implement this in swift 3 but not getting any thing.

I refer this link but its not working in swift 3.

Please help me.

Community
  • 1
  • 1
Ekta Padaliya
  • 5,743
  • 3
  • 39
  • 51
  • 1
    What do you want to achieve by swizzling the methods? Are you writing test cases and want to replace the URL calls or just debugging? – John Dough May 02 '17 at 06:55
  • @JohnDough I searching for a way to accomplish exactly that. Any ideas how to do it? – rraallvv Aug 26 '20 at 05:54

2 Answers2

1

we can swizzle methods in swift as follows

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) 

//try like this using subclass

     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!
}
}
Satyanarayana
  • 1,059
  • 6
  • 16
0

I have tried with simple NSURLSession swizzling and it did work, however while trying to achieve swizzling of Alamorfire and other third party Network SDK, it didn't work, since we need to swizzling from base of URLProtocol, implement URLSessionConfiguration.default with swizzling method and add all properties like startLoading, stopLoading, init and canInit feature. Also add URLSession delegate method in order to return values.

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

Kashif Jilani
  • 1,207
  • 3
  • 22
  • 49