xplatsolutions / iOS-Network-Interceptor

A set of classes that will allow you to monitor any request using NSURLConnection or NSURLSession.
MIT License
2 stars 3 forks source link

How to if Using delegate instead of block #1

Open ekingo opened 7 years ago

ekingo commented 7 years ago

most of the times, use NSURLSession to send request with Delegate instead of block. so the completionHandler is nil, and there is no way to enter the notify block.

ekingo commented 7 years ago
  • (void) injectImplementationToNSURLSession { // Replace the method on the same class that's used // in the calling code Class class = [NSURLSession class];
// The Original NSURLSession selector
SEL originalSelector = @selector(sessionWithConfiguration:delegate:delegateQueue:);

// The Replacement method implementation
IMP replacement = (IMP)XplatNSURLSessionWithConfigurationDelegateAndQueue;

// This will eventually hold the original sessionWithConfiguration:delegate:delegateQueue:
IMP* store = (IMP*)&OriginalNSURLSessionWithConfigurationDelegateAndQueue;

IMP originalImp = NULL;
Method method = class_getClassMethod(class, originalSelector);
if (method)
    {
    const char* type = method_getTypeEncoding(method);
    // Replace the original method with the XplatNSURLSessionWithConfigurationDelegateAndQueue
    originalImp = class_replaceMethod(class, originalSelector, replacement, type);
    if (!originalImp)
        {
        originalImp = method_getImplementation(method);
        }
    }

// Put the original method IMP into the pointer
if (originalImp && store)
    {
    *store = originalImp;
    }
}

It should :

class_getInstanceMethod