1

I have been trying to swizzle the dataTaskWithURL method of NSURLSession class.This is what i have tried

+ (void)swizzleDataTaskWithRequest {
Class class = [self class];

SEL originalSelector = @selector(dataTaskWithRequest:completionHandler:);
SEL swizzledSelector = @selector(my_dataTaskWithRequest:completionHandler:);

Method originalMethod = class_getInstanceMethod(class, originalSelector);
Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);

BOOL didAddMethod = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod),method_getTypeEncoding(swizzledMethod));

if (didAddMethod) {
    class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod),method_getTypeEncoding(originalMethod));
} else {
    method_exchangeImplementations(originalMethod, swizzledMethod);
}
}


- (NSURLSessionDataTask *)my_dataTaskWithURL:(NSURL *)url completionHandler:(void (^)(NSData * __nullable data, NSURLResponse * __nullable response, NSError * __nullable error))completionHandler{


NSLog(@"***************************");

return [self my_dataTaskWithURL:url completionHandler:completionHandler];
}

And this my_dataTaskWithURL i wanted to pass own completion handler and i do not know how to create that

Thanks in advance !!

Manu Gupta
  • 1,759
  • 1
  • 14
  • 22
  • 1
    Possible duplicate of [How to swizzle NSURLSession class method dataTaskWithUrl](http://stackoverflow.com/questions/35570809/how-to-swizzle-nsurlsession-class-method-datataskwithurl) – Borys Verebskyi Mar 04 '16 at 11:56

2 Answers2

1

Before deciding to use the class_replaceMethod technique - you should read up on using method_setImplementation alongside c-implementations.

method_setImplementation returns the original implementation which you can then store and call directly. In contrast, when you use exchangeImplementations this original implementation is available only through your swizzling Method typedef. This will cause the hidden selector _cmd that's passed along with Self into the method call to be your swizzling method's selector. This can cause problems when the user's method depends on the correct _cmd (selector) parameter.

This is a good resource:

https://blog.newrelic.com/2014/04/16/right-way-to-swizzle/

dcrow
  • 570
  • 5
  • 11
0

If you are achieving swizzling of only NSURLSession then this will got going to work with Alamofire and others third party SDK. You need to go for base swizzling with URLProtocol. Below is the gist link which will be very helpful for everyone.

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

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