UIWebView intercepts resource requests

Posted by alphamic on Fri, 01 May 2020 06:01:15 +0200

In the project, the web page burying point initiates the request in the form of loading the resource file. When the client intercepts the request, it requests to give up sending the request, instead, the client counts the burying point event.

Solution
NSURLProtocol can intercept and listen to the request requests made in each URL Loading System. (if it's not for the requests from these classes, NSURLProtocol can't intercept and listen.)

NSURLProtocol is a virtual base class, so you can't use it directly. To use it, you must customize a class to be its subclass, and then implement some methods that must be implemented in it

+ (BOOL)canInitWithRequest:(NSURLRequest *)request {
    /*
    //Prevent dead circulation, use if necessary
    if ([NSURLProtocol propertyForKey:protocolKey inRequest:request]) {
        return NO;
    }
    */
    NSString * urlString = request.URL.absoluteString;
    //Need to process request return YES
    return [WebViewStatistics webViewSendStatisticsWithURL:uslString];
}

+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request {
    // return request;
    //Intercept directly here and don't send
    return nil;
}

// If you need to resend the request, you can process it in the following methods. If you do not implement the following methods, the request will end in the form of timeout.
// Step in the pit: at the beginning, it returns to request normally. The following methods are not implemented. The timeout of the result request loading affects the webView loading completion callback agent method. Finally, when the request is returned, nil is returned directly, and the request is no longer initiated.
- (void)startLoading {
}

- (void)stopLoading {
}

In addition to these, you need to register this subclass when the program starts:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    [NSURLProtocol registerClass:[IFStatisticsURLProtocol class]];

    return YES;
}

Assign a value to the protocolClasses property of NSURLSessionConfiguration when the request is initiated (consider using the Method Swizzling method):

NSURLSessionConfiguration * configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
configuration.protocolClasses = @[[IFStatisticsURLProtocol class]];

Logging: at first, I thought that all requests loaded by webView would call the proxy method, o( ̄)  ̄) o

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
     return YES;
}