如何调酒NSURLSession方法dataTaskWithUrl

问题描述:

我一直在努力调配NSURLSession class.This的dataTaskWithURL方法是什么,我都试过如何调酒NSURLSession方法dataTaskWithUrl

+ (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]; 
} 

这my_dataTaskWithURL我想通过自己的完成处理程序,我不知道如何创建

在此先感谢!

+1

[如何调酒NSURLSession类方法dataTaskWithUrl](可能的重复http://stackoverflow.com/questions/35570809/how-to-swizzle-nsurlsession -class-method-datataskwithurl) –

在决定使用class_replaceMethod技术 - 你应该使用method_setImplementation沿着C-实现读了。

method_setImplementation返回您可以直接存储和调用的原始实现。相反,当你使用这个exchangeImplementations原始的实现只有通过您的交叉混合方法的typedef可用。 _cmd一个与自我一起传递到方法调用是你混写方法的选择,这将导致隐藏的选择。这可能会导致问题,当用户的方法取决于正确_cmd(选择)参数。

这是一个很好的资源:

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

+1

请不要只链接到外部网站作为您的答案。链接是不稳定的。 – Tyler

+1

加了更多,谢谢 – crow

+0

谢谢,欢迎来到Stack Overflow :) – Tyler