iphonejailbreaknsurlsessiontheoslogos

How to hook NSURLSession methods with theos?


I created a tweak project using rpetrich's theos and wanted to hook NSURLSession methods but the hooks don't seem to get invoked? Why? This is my Tweak.xm code:

%hook NSURLSession

- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request
                            completionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandler
{
    NSLog(@"testhook dataTaskWithRequest:completionHandler:");
    return %orig(request, completionHandler);
}

- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request
{
    NSLog(@"testhook dataTaskWithRequest");
    return %orig(request);
}

%end

%hook NSMutableURLRequest

+ (id)requestWithURL:(NSURL *)URL
{
    NSLog(@"testhook NSMutableURLRequest");
    return %orig(URL);
}

%end

I added the NSMutableURLRequest hook to make sure that the file and the whole tweak was being loaded. I can verify that it does hook requestWithURL: but not any of the NSURLSession methods. I am testing against the code from NSURLSessionExample.

What's missing here? Has anybody successfully hooked NSURLSession?


Solution

  • NSURLSession is a class cluster, and you are hooking the toplevel class that contains no (or scarce little) code.

    You should investigate the subclasses of NSURLSession—potentially by logging the real class of an NSURLSession object in-situ. In my limited testing, I received an object whose class was truly named __NSURLSessionLocal.