如何调配NSURLSession方法dataTaskWithUrl

时间:2016-02-25 14:35:05

标签: ios xcode runtime swizzling

我一直在尝试调用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我想传递自己的完成处理程序,我不知道如何创建

提前致谢!!

2 个答案:

答案 0 :(得分:1)

在决定使用class_replaceMethod技术之前 - 您应该阅读使用method_setImplementation和c-implementation。

method_setImplementation返回原始实现,然后您可以直接存储和调用。相反,当您使用exchangeImplementations时,此原始实现仅可通过您的混合方法typedef获得。这将导致与Self一起传递的隐藏选择器_cmd进入方法调用,成为您的混合方法的选择器。当用户的方法取决于正确的_cmd(选择器)参数时,这可能会导致问题。

这是一个很好的资源:

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

答案 1 :(得分:0)

如果仅实现NSURLSession,那么它将可以与Alamofire和其他第三方SDK一起使用。您需要使用URLProtocol进行基本调整。下面是要点链接,它将对每个人都非常有帮助。

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