Ios 如何使用URL swizzle NSURLSession方法DataTask
我一直在尝试使用NSURLSession类的dataTaskWithURL方法,这就是我所尝试的Ios 如何使用URL swizzle NSURLSession方法DataTask,ios,xcode,runtime,swizzling,Ios,Xcode,Runtime,Swizzling,我一直在尝试使用NSURLSession类的dataTaskWithURL方法,这就是我所尝试的 + (void)swizzleDataTaskWithRequest { Class class = [self class]; SEL originalSelector = @selector(dataTaskWithRequest:completionHandler:); SEL swizzledSelector = @selector(my_dataTaskWithRequest:compl
+ (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,我不知道如何创建它
提前谢谢 在决定使用class_replaceMethod技术之前,您应该阅读有关在c语言实现的同时使用
method_setImplementation
method\u setImplementation
返回原始实现,然后可以直接存储和调用。相反,当您使用ExchangeImplements
时,此原始实现仅通过swizzling方法typedef可用。这将导致与Self一起传递到方法调用中的隐藏选择器_cmd成为swizzling方法的选择器。当用户的方法依赖于正确的_cmd(选择器)参数时,这可能会导致问题
这是一个很好的资源:
如果您仅实现NSURLSession的swizzling,那么这将与Alamofire和其他第三方SDK一起使用。您需要使用URLProtocol进行基本swizzling。下面是对大家非常有帮助的要点链接
可能重复的请不要仅仅链接到外部站点作为您的答案。链接是不稳定的。